void foo(char *p)
{
int i;
int len = strlen(p);
p = malloc(sizeof(char)*len+2);
p[0] = '1';
for(i=1; i<len+1; i++)
p[i] = '0';
p[i] = '\0';
}
int main()
{
char p[2] = "1";
foo(p);
printf("%s\n", p); // "10" expected
return 0;
}
I realized that when I call malloc in foo, p‘s value has been changed, so array p in main will not be influence. But I don’t know how to correct it.
You have a few wrong things with your code:
In
main, you declarepas an array that resides on the stack. Things that are on the stack cannot later be resized.Then in
fooyou want to changepto point to memory from the heap rather than to the array you have declared.What you want to achieve can be done by initially allocating
pwithmalloc, and then reallocating that memory again withrealloc:Notice that the argument of
foois a double pointer. That’s because realloc may not only resize the memory block, but it may actually move it as well, so it will affect the value of the pointer.Also note that the second argument of
reallocis not the size you want to increment with, but rather the current size of the block plus the size to increment with.