How to set pointer reference through a function
In C, I am trying to set a pointer's value by sending it to a function, but the value wont change outside of the function. Here is my code:
#include <stdio.h>
void foo(char* str) {
char* new_str = malloc(100);
memset(new_str, 0, 100);
strcpy(new_str, (char*)"new test");
str = new_str;
}
int main (int argc, char *argv[]) {
char* str = malloc(100);
memset(str, 0, 100);
strcpy(str, (char*)"test");
foo(str);
printf("str = %s\n", str);
}
I want to print out:
str = new test
but this code prints开发者_StackOverflow社区 out:
str = test
Any help will be appreciated. Thanks in advance.
There is no pass-by-reference in C. If you provide str
as the argument to a function in C, you are always passing the current value of str
, never str
itself.
You could pass a pointer to str into the function:
void foo(char** pstr) {
// ...
*pstr = new_str;
}
int main() {
// ...
foo(&str);
}
As Eiko says, your example code leaks the first memory allocation. You're no longer using it, and you no longer have a pointer to it, so you can't free it. This is bad.
You need to use pointer to the pointer, untested:
#include <stdio.h>
void foo(char** str)
{
char* new_str = malloc(100);
memset(new_str, 0, 100);
strcpy(new_str, (char*)"new test");
if (str) { /* if pointer to pointer is valid then */
if (*str) /* if there is a previous string, free it */
free(*str);
*str = new_str; /* return the string */
}
}
int main (int argc, char *argv[])
{
char* str = malloc(100);
memset(str, 0, 100);
strcpy(str, (char*)"test");
foo(&str);
printf("str = %s\n", str);
}
You are just reassigning a pointer, which is a local variable in foo.
If you want to copy the string, use strcpy(str, new_str);
You could pass a reference to the pointer instead and reassign, but this can easily lead to memory leaks and is hard to maintain.
Edit: For the pseudo pass by reference see the answer by Steve.
I did it this way by returning the pointer from the function. There is no reason to use malloc in this case, so you don't have to worry about freeing.
gcc 4.4.3 c89
char* print_test(char *str)
{
char *new_str = "new_test";
printf("new_str [ %s ]\n", new_str);
str = new_str;
return str;
}
int main(void)
{
char *str = "test";
printf("str [ %s ]\n", str);
str = print_test(str);
printf("str [ %s ]\n", str);
return 0;
}
精彩评论