f()调用后ptr,我希望它指向值为 的单个字节A。但而是ptr按值复制,并且仅在函数中可用f(?)我做错了什么?
void f(char* ptr) {
ptr = (char*) malloc(1);
*ptr = 'A';
}
int main() {
char* ptr;
f(ptr);
printf("%c\n", *ptr); // Segmentation fault, But it should be 'A'
// free(ptr);
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
是的,它是按值传递的。如果您希望对指针所做的更改在调用站点可见,则需要向该指针传递一个指针。
例子:
#include <stdlib.h>
#include <stdio.h>
void f(char **ptr) { // pointer to the pointer
*ptr = malloc(1);
if(*ptr) // precaution if malloc should fail
**ptr = 'A';
}
int main(void) {
char *ptr;
f(&ptr); // take the address of `ptr`
if(ptr) // precaution again
printf("%c\n", *ptr); // now fine
free(ptr); // without this, you have a memory leak
}
Run Code Online (Sandbox Code Playgroud)