我是 C 的新手。我试图将一个变量的地址传递给一个函数,然后让该函数将一个 char 指针分配给传递的这个变量地址。编译器没有报错,但代码也不能正常工作。
typedef enum {
VAL_1,
VAL_2
} member_type;
char *a1="Test 123";
int func (member_type x, char *temp) {
switch(x) {
case VAL_1:
temp = a1;
return 1;
case VAL_2:
return 2;
}
return 0;
}
int main(){
member_type b;
static char *d1;
b = VAL_1;
printf("%p\n",&d1);
func(b, &d1);
printf("Val_1:%s\n",d1);
return 0;
}
执行时出现如下错误:
-bash-3.00$ ./a.out
0x500950
Name:(null)
谁能帮我解决这个问题?
最佳答案
我觉得奇怪的是你的编译器没有提示。我怀疑您在没有警告的情况下进行编译。您应该始终使用启用的 -Wall
选项进行编译(假设您使用的是 GCC 或 clang)。
你做错的是,虽然你将 char *
指针的地址传递给你的函数,但你只修改了该指针的本地副本(函数参数在 C 中按值传递), 在函数外没有影响。您应该做的是将函数参数声明为指向指针的指针,并通过取消引用其地址来修改原始指针:
void func(const char **p) // notice the pointer-to-pointer...
{
*p = "bar"; // and the dereference (*) operator
}
const char *p = "foo";
printf("Before: %s\n", p);
func(&p);
printf("After: %s\n", p);
这打印:
Before: foo
Afte: bar
关于c - 将变量地址传递给 C 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18154595/