在void函数中返回结构指针

时间:2013-03-16 19:41:47

标签: c++ pointers struct return-value void-pointers

我是新的c ++编程,只是从结构和指针开始,我有一个疑问。

我有一个struct和void function()

struct my_struct 
{
int x;
}

void my_function(){

my_struct* x=10

}

我需要将my_struct * x的值返回给调用函数。

我看到返回结构指针的大部分示例都不使用void function(),而是像这样使用

struct my_struct 
    {
    int x;
    }

    struct my_struct* my_function( int* x){

    //assign the value for X and return by assign a reference `&` from caller function

    } 

所以不可能从void函数返回结构指针或者我是否需要使用void指针?请耐心等待我帮助我,我是编程新手。

2 个答案:

答案 0 :(得分:1)

首先:

void my_function() {
    my_struct* x=10
}

是非法的。我不认为你完全理解指针的含义。要返回值,您必须:

  • 使用my_struct* my_function()
  • 设置返回值
  • 或定义哪个外部变量应存储返回值:my_struct* my_function(my_struct**);

以下是使用动态分配的一些示例:

my_struct* my_function() {
    return new my_struct { 10 };
}

或:

void my_function(my_struct** var) {
    *var = new my_struct { 10 };
}

如果有意义,最好在可能的情况下使用返回值。当您需要从单个函数中返回多个值时,可以使用第二种方法。

答案 1 :(得分:0)

要在不使用返回类型的情况下向调用者报告值,您可以填写调用者提供的缓冲区。这通常被称为“输出参数”。

void my_function( my_struct** result )
{
   my_struct* x = new my_struct{ 10 };
   //...
   *result = x;
}