C program, pointer argument won't hold values

核能气质少年 提交于 2019-12-04 18:48:35

Everything in C is passed by value, so when you perform the assignment:

v = (int*) realloc(v,n*sizeof(int));

You are assigning a new value to the local copy of the variable v. If you want to change the value of the pointer itself (as opposed to modifying what the pointer already points to) you will need to pass a pointer to a pointer and dereference it once to perform the assignment, i.e.,

int ModifyPointer( int **v )
{
    // error checking and whatnot
    *v = realloc(*v,n*sizeof(int));
}

Think of it this way; you have a pointer p that resides at memory address 0xA and points to memory address 0xFF. You pass p to a function and a copy v is created. The copy v resides at memory address 0x2A, but still points to memory address 0xFF.

                     p(0xA)      v(0x2A)
                       |            |
                        \          /
                         \        /
                          \      /
                            0xFF

So, when you dereference either pointer you end up referring to the same chunk of memory, but the pointers themselves live in different places in memory. Thus, when you modify the value of the copy it is not reflected in the original (i.e., realloc is creating a new pointer in a new memory location and assigning it to the variable v, but p remains unchanged.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!