繁体   English   中英

将变量的地址传递给C函数

[英]passing address of variable to a C function

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

你需要一个双重解除引用:

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 = USERNAME;
  printf("%p\n",&d1);

  func(USERNAME, &d1);

  printf("Val_1:%s\n",d1);

  return 0;
}

复制你的代码并在func中只进行了两次更改:1)char ** temp和* temp = a1。 回想一下,a1是指针,是* temp。

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;   // need to dereference the double ptr
                return 1;

            case VAL_2:
                return 2;
 }
 return 0;
}

int main(){

  member_type  b;
  static char   *d1;

  b = VAL_1;
  printf("%p\n", &d1);     // point to the pointer d1

  func(b, &d1);      // point to the pointer d1

  printf("Val_1:%s\n",d1);

  return 0;
}

在Eclipse / Microsoft C编译器上运行此代码,并打印:

004054A0
Val_1:Test 123

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM