asi*_*man 7 c pointers function pass-by-value
我正在向指针传递一个更新它的函数.但是,当函数返回指针时,它返回到函数调用之前的值.
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
static void func(char *pSrc) {
int x;
for ( x = 0; x < 10; x++ ) {
*pSrc++;
}
printf("Pointer Within Function: %p\n", pSrc );
}
int main(void) {
char *pSrc = "Good morning Dr. Chandra. This is Hal. I am ready for my first lesson.";
printf("Pointer Value Before Function: %p\n", pSrc );
func(pSrc);
printf("Pointer Value After Function: %p\n", pSrc );
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
这是输出
Pointer Value Before Function: 0x100403050
Pointer Within Function: 0x10040305a
Pointer Value After Function: 0x100403050
Run Code Online (Sandbox Code Playgroud)
我期待的是函数之后匹配函数内的值的值.
我尝试切换到char **pSrc
但没有达到预期的效果.
我相信答案很简单,但我是一名正在恢复的硬件工程师,似乎无法弄清楚:-)
函数内部的指针是传递指针的副本.
它们都保持相同的地址但具有不同的地址,因此更改其中一个地址所持有的地址不会影响另一个地址.
如果你想增加函数内部的指针,则传递它的地址,就像这样
static void func(char **pSrc) {
int x;
for ( x = 0; x < 10; x++ ) {
(*pSrc)++;
}
printf("Pointer Within Function: %p\n", pSrc );
}
Run Code Online (Sandbox Code Playgroud)
和
func(&pSrc);
Run Code Online (Sandbox Code Playgroud)
另外,请注意不要修改内容,因为指针指向字符串文字,并且不能修改字符串文字.