-1

我想从双指针访问结构的成员,但出现错误

“错误:'('令牌之前的预期标识符”

struct test{
  struct foo **val;
};

struct foo{
  int a;
}

int main (){
  struct test *ptr = (struct test *)malloc(sizeof(struct test));
  ptr->val = &foo;
  /*foo is already malloced and populated*/
  printf ("Value of a is %d", ptr->(*val)->a);
}

我也试过:

*ptr.(**foo).a
4

2 回答 2

0

你想这样做:

#include <stdio.h>
#include <stdlib.h>

struct test {
    struct foo **val;
};

struct foo {
    int a;
};

int main(void) {
    struct test* test_ptr = malloc(sizeof(struct test));
    struct foo* foo_ptr = malloc(sizeof(struct foo));
    foo_ptr->a = 5;    // equivalent to (*foo_ptr).a = 5;
    test_ptr->val = &foo_ptr;
    printf ("Value of a is %d\n", (*(test_ptr->val))->a);
    free(test_ptr);
    free(foo_ptr);
    return 0;
}

输出:

C02QT2UBFVH6-lm:~ gsamaras$ gcc -Wall main.c 
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
Value of a is 5

在我的例子中:

  1. 我为 a 动态分配空间struct test
  2. 我为 a 动态分配空间struct foo
  3. 我将值 5 分配给 的a成员foo_ptr
  4. 我将分配对象的地址分配给的struct foo成员valtest_ptr
  5. 我打印成员a双指针val指向的结构。

请注意,在您的示例中:struct foo是一种类型,因此询问其地址是没有意义的。

此外,当您完成声明struct foo.

哦,请确保不要强制转换 malloc() 的返回值

于 2016-08-29T01:02:08.983 回答
-2

in ptr->val = &foo;, foo 是一个结构体(你在第 5 到 7 行声明了它)。取其地址不会给出 a **,而只会给出 a *

此外,似乎多个事物具有相同的名称;a是结构foo名称还是它的实例,或两者兼而有之?

然后,当您取消引用它时:ptr->(*val)->a似乎是错误的顺序。就像ptr->val地址一样foo(那是你在上面一行中分配的),会ptr->(*val)是什么?

我想ptr->val.a会给你你的a. 但是, the 仍被val声明为 a**并始终用作 a *。它可能有效,但没有多大意义。

于 2016-08-29T00:46:01.753 回答