1

I'm relatively new to C. I'm trying to pass an address of a variable to a function, and then have that function assign a char pointer to this variable address which was passed. The compiler doesn't complain, but the code doesn't work properly either.

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;
}

I get the following error when I execute it:

-bash-3.00$ ./a.out
 0x500950
 Name:(null)

Can anyone help me with how to fix it?

4

3 回答 3

3

我觉得你的编译器没有抱怨很奇怪。我怀疑你在编译时没有警告。您应该始终使用-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
于 2013-08-09T19:57:04.757 回答
1

您需要双重取消引用:

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;
}
于 2013-08-09T19:55:03.833 回答
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
于 2013-08-09T22:25:09.520 回答