如何增加函数参数指向的块的大小?
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;
}
我意识到当我在foo
中调用malloc
时,p
的值已经改变,所以数组p
在主要不会有影响。但我不知道如何纠正它。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码有一些错误:
在
main
中,您将p
声明为驻留在堆栈上的数组。堆栈上的内容以后无法调整大小。然后在
foo
中,您希望将p
更改为指向堆中的内存,而不是指向您声明的数组。可以通过首先使用
malloc
分配p
,然后使用realloc
再次重新分配该内存来完成:您想要实现的目标 请注意,
foo
是一个双指针。这是因为 realloc 不仅可以调整内存块的大小,而且实际上还可以移动内存块,因此它会影响指针的值。另请注意,realloc 的第二个参数不是要递增的大小,而是块的当前大小加上要递增的大小。
You have a few wrong things with your code:
In
main
, you declarep
as an array that resides on the stack. Things that are on the stack cannot later be resized.Then in
foo
you want to changep
to 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
p
withmalloc
, and then reallocating that memory again withrealloc
: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.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.您需要传递指针的地址并以
char**
作为函数参数,即传递&p
作为参数并使用*p 在
foo
中获取数组地址。顺便说一句,数组的初始化需要完成char p[2] = {'1'}
;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
insidefoo
to get the array address. BTW, the initialization of array needs to be donechar p[2] = {'1'}
;