c - 将变量地址传递给 C 函数

标签 c string pointers char memory-address

我是 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/

相关文章:

c - 如何将结构体成员写入文件?

java - 如何在 Java 中将字符串与 UTF8 字节数组相互转换

c - 如何在 C 中检测/分析内存(堆、指针)读写?

c - 试图理解 XV6 上的 UNIX 系统调用

c++ - 包含指向自身的智能指针的对象,在对象超出范围之前不会重置

c - 如何从cgo到exe

c - IRC 通信细节

c - 802.11数据包的大小

ios - 如何从 Swift 字符串中选择大写字母?

string - 如何使用传递的字符串进行转换?