0

Hey guys I'm having a little difficulty understanding how to have a pointer point to another pointer in a struct, that thereby points to another pointer in a struct. Not sure if that makes sense.

Basically, usually I would write something like:

test->first = NULL;

But I need to access a part of first as well. I am trying:

test->first->alpha = NULL;

But that isn't working. Any ideas on how I can access the alpha by only declaring test? And thereby set test->first->alpha to NULL?

Thanks guys!

4

3 回答 3

1

除非您分配一个有效的指针,否则您test->first无法访问test->first->alpha. 如果你仍然这样做,你会取消引用一个无效的指针,这会导致未定义的行为和可能的崩溃。

于 2013-09-17T17:35:39.703 回答
1

如果你问如何声明这样的结构,这里有一个例子:

 struct First {
     int alpha;
 };
 struct Test {
     struct First* first;
 };

正如其他人指出的那样,在尝试取消引用之前,您必须确保 test->first 指向某个地方,如下所示:

struct Test* test = malloc(sizeof(struct Test));
test->first = malloc(sizeof(struct First));
test->first->alpha = 123;
于 2013-09-17T17:39:57.830 回答
0

如果first它自己指向NULL,那么访问alpha它会导致未定义的行为。

确保first指向有效的内存位置,然后您可以分配它的成员。

于 2013-09-17T17:36:43.827 回答