-4

i am new c++ programming and just started with structures and pointers and i got a doubt.

i have a struct and void function()

struct my_struct 
{
int x;
}

void my_function(){

my_struct* x=10

}

i need to return the value of my_struct* x to calling function.

most of the examples i saw returning a struct pointer doesn't use void function() instead they use like this

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

    } 

so is it not possible to return a struct pointer from a void function or do i need to use void pointers? pls bear with me and help me i am new to programming.

Rd7
  • 45
  • 2
  • 9
  • 1
    Return type of `void` means "function doesn't return a value." If you need to return something, give the function the appropriate return type. That would be `my_struct*` in your case. – Angew is no longer proud of SO Mar 16 '13 at 19:43
  • 1
    Also, `my_struct* x=10` is illegal – Andy Prowl Mar 16 '13 at 19:43
  • If you don't fully understand functions and pointers don't try to return a pointer dinamically allocated inside a function call. You may end up causing memory leaks if you forget to delete them afterwards. Pass the struct by reference if possible. Otherwise, take a look to smart pointers in boost libraries. – FKaria Mar 16 '13 at 20:05

2 Answers2

1

First of all:

void my_function() {
    my_struct* x=10
}

is illegal. I don't think you fully understood the meaning of pointers. To return a value you have to:

  • Either set a return value with my_struct* my_function()
  • or define which outside variable should store the returned value: my_struct* my_function(my_struct**);.

Here's some examples using dynamic allocation:

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

or:

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

If it makes sense to, it is good practice to use a return value when possible. You can use the second approach when you need multiple returned values from a single function.

Shoe
  • 74,840
  • 36
  • 166
  • 272
  • @jueecySo if i need to the print the value of *var, should i print in this void function () or should print in the caller function. – Rd7 Mar 17 '13 at 08:26
  • @Rd7, If your function is supposed to print the variable, in the function. Otherwise in the caller function. – Shoe Mar 17 '13 at 16:36
0

To report values to a caller without using the return type, you can fill in a caller-provided buffer. This is often called an "out parameter".

void my_function( my_struct** result )
{
   my_struct* x = new my_struct{ 10 };
   //...
   *result = x;
}
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720