user3108849
user3108849

Reputation: 111

Returning pointer error from a function in C

I am sending 2 strings to a function with pointers, and I expect one of them to change when they get back to main function. but it just returns null, as it shouldn't.

int main (){
...
char *str1="SOME RANDOM INPUT";
char *str2=NULL;
function1 (str1, str2);
...
}

void function1 (char mystr, char *output){
 char *input = strtok(mystr, " ");
 if (input != NULL)
      output = input;

 return;
}

what am I doing wrong here?

Upvotes: 2

Views: 626

Answers (2)

Manos
Manos

Reputation: 2186

You should always have in mind that C, pass the parameters always by value and not by reference.

Show for example assume that with the code

char *str1="SOME RANDOM INPUT";

str1holds a memory location e.g. 0x008000

when you call function1 (str1, str2); the memory location of str1 will be copied to the parameter variable input, whose scope is restricted inside the scope of the function of course. input has the same contents with str1 but they are placed in completely different memory locations. So by altering input value you do not affect str1.

The solution is to use double pointer. (In C++ you could use call by reference with the & operator)

Upvotes: 2

Ashalynd
Ashalynd

Reputation: 12573

I think you should work with pointers to pointers to get the pointer changed, like that:

int main (){
...
char *str1="SOME RANDOM INPUT";
char *str2=NULL;
function1 (&str1, &str2);
...
}

void function1 (char **input, char **output){
 ...
 if (*input != NULL)
      *output = *input;

 return;
}

Upvotes: 4

Related Questions