在函数内部更改指针不会在函数外部反映 [英] Changing the pointer inside a function does not reflect outside the function
问题描述
void alloco(int *ppa)
{
int i;
printf("inside alloco %d\n",ppa);
ppa = (int *)malloc(20);
ppa[15] = 9;
printf("size of a %d \n", sizeof(ppa));
for(i=0;i<20;i++)
printf("a[%d] = %d \n", i, ppa[i]);
}
int main()
{
int *app = NULL;
int i;
printf("inside main\n");
alloco(app);
for(i=0;i<20;i++)
printf("app[%d] = %d \n", i, app[i]);
return(0);
}
基本上,我要做的就是将空指针从我的main
传递给一个函数(alloco
),该函数分配内存/填充指针所指向并返回的相同位置.我正在正确获取位于函数(alloco
)中但不在main
中的局部打印.
Basically all I wanted to do is to pass a null pointer from my main
to a function(alloco
) which allocates memory/fills the same location the pointer is pointing to and returns. I am getting local prints correctly that is inside function(alloco
) but not in main
.
我在这里做错什么了吗?
Am I doing anything wrong here?
推荐答案
您需要这样做:
void alloco(int **ppa)
{
int i;
printf("inside alloco %p\n",ppa);
*ppa = malloc(20 * sizeof(int));
(*ppa)[15] = 9; // rather pointless, in the loop below (*ppa)[15] will be
// overwritten anyway
printf("size of a %d \n", sizeof(*ppa)); // rather pointless, not sure
// what you want to print here
for(i = 0; i < 20; i++)
printf("a[%d] = %d \n", i, (*ppa)[i]);
}
int main()
{
int *app = NULL; // you can drop the '= NULL', it's useless, because
int i; // alloco(&app) will change the value of app anyway
printf("inside main\n");
alloco(&app);
for(i = 0; i < 20; i++)
printf("app[%d] = %d \n", i, app[i]);
return 0;
}
在您的程序中,您将传递一个指向alloco
的指针,该指针将位于ppa
参数中.此ppa
参数就像alloco
内部的局部变量,并且在对其进行修改时,将不会修改您在main
(app
)中传递给函数的原始值.
In your program you pass a pointer to alloco
which will be in the ppa
parameter. This ppa
parameter is just like a local variable inside of alloco
and when you modify it, the original value you passed to the function in main
(app
) won't be modified.
在更正的版本中,我们将 pointer 传递给app
.在alloco
中,我们取消引用该指针并将其分配的值写入其中.
In the corrected version, we pass a pointer to app
. In alloco
we dereference that pointer and write the malloced value to it.
这篇关于在函数内部更改指针不会在函数外部反映的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!