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] = '
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.
我意识到当我在foo中调用malloc时,p的值已经改变,因此main中的数组p不会受到影响。但我不知道如何纠正它。
2 个解决方案
#1
2
You have a few wrong things with your code:
你的代码有一些错误的东西:
In main, you declare p as an array that resides on the stack. Things that are on the stack cannot later be resized.
在main中,您将p声明为驻留在堆栈上的数组。堆栈上的东西以后不能调整大小。
Then in foo you want to change p to point to memory from the heap rather than to the array you have declared.
然后在foo中你想要改变p指向堆中的内存而不是你声明的数组。
What you want to achieve can be done by initially allocating p with malloc, and then reallocating that memory again with realloc:
您想要实现的目标可以通过最初使用malloc分配p,然后使用realloc重新分配该内存来完成:
void foo (char **p) {
*p = realloc(*p, 4);
}
int main (void) {
char *p = malloc(2);
foo(&p);
...
}
Notice that the argument of foo is 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.
请注意,foo的参数是双指针。这是因为realloc不仅可以调整内存块的大小,而且实际上也可以移动它,因此它会影响指针的值。
Also note that the second argument of realloc is not the size you want to increment with, but rather the current size of the block plus the size to increment with.
另请注意,realloc的第二个参数不是您要增加的大小,而是块的当前大小加上要增加的大小。
#2
2
You need to pass the address of the pointer and take char** as the function argument, i.e. pass &p as the argument and use *p inside foo to get the array address. BTW, the initialization of array needs to be done char p[2] = {'1'};
你需要传递指针的地址并将char **作为函数参数,即传递&p作为参数,并在foo中使用* p来获取数组地址。顺便说一句,数组的初始化需要完成char p [2] = {'1'};
';
}
int main()
{
char p[2] = "1";
foo(p);
printf("%s\n", p); // "10" expected
return 0;
}
void foo(char *p)
{
int i;
int len