问题描述
我有一个编程任务,我偶然发现了这个小问题:当我给函数一个指针作为参数时,我无法改变它指向的地址。我通过返回我希望指针指向的新地址来解决这个问题。但我仍然想知道为什么不能操作指针参数,因为所有内存分配函数都使用返回值而不是参数列表。
我可能做错了什么?或者是否真的不可能改变指针?有没有人有解释?
例子:
void foo( int * ptr)
{
ptr = malloc(sizeof(int));
} / *在调用这个函数后,我会
期望指针变成了
新分配的内存,但它保持为NULL * /
int main()
{
int * ptr = NULL;
foo(ptr);
返回0;
内存分配函数返回指针值,所以它通常被分配给一个指针
。
传递一个函数指针作为参数是一个不同的故事,
因为改变它不会更改原始值(按值传递)。这是
为什么我们在这些情况下使用指针,给变量
的地址并在函数中更改其值。
如果需要要传递一个指针,并改变它指向的内容,使用
a指针指向一个指针!
void
my_function(int **指针)
{
* pointer =& something; //将改变指针地址
}
int * my_pointer =& something_else;
my_function(&my_pointer);
I had a programming assignment a while back where I stumbled upon this little problem: when I gave a function a pointer as a parameter, I could not change the address it pointed at. I solved that by returning the new adress I wanted the pointer to point to. But I am still wondering why it's not possible to manipulate a pointer parameter because all memory allocating functions work with a return value as well instead of a parameter list.
Was I possibly doing something wrong? Or is it really not possible to change the pointee? Does anyone have an explanation?
Example:
void foo(int *ptr)
{
ptr=malloc(sizeof(int));
} /* after calling this function I would
expect the pointee to have changed to the
newly allocate memory but it stays NULL*/
int main()
{
int *ptr=NULL;
foo(ptr);
return 0;
}
Memory allocating functions return the pointer value, so it is generallyassigned to a pointer.
Passing a pointer to a function as an argument is a different story,because changing it won't change the original (pass by value). That'swhy we use pointers in these cases, to give the address of a variableand change its value in the function.
If you need to pass a pointer instead, and change what it points to, usea pointer to a pointer!
void
my_function(int **pointer)
{
*pointer = &something; // will change the pointer address
}
int *my_pointer = &something_else;
my_function(&my_pointer);
这篇关于给函数中的指针分配一个新的地址是不可能的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!