在结构体中访问指针

3

目前我有以下代码:

typedef struct _hexagon {
    int *vertice[6];
    int *path[6];
    int resourceType;
} hexagon;


typedef struct _game {
    hexagon hexagons[5][5];
} Game;

主要内容如下:

Game g;
// This is the line that fails
g.hexagons[0][0].vertice[0] = 0;

这个程序能够编译通过但是运行时会导致分段错误。我尝试了很多变化,例如:

g.hexagons[0][0].*vertice[0] = 0;

编译失败。如何从结构体内部访问指针的内存?


为什么vertices是int*数组而不是int数组? - Doug Richardson
另外,你说的那段代码在我的 Mac OS X 上没有出现段错误。你用的是什么系统? - Doug Richardson
@DougRichardson 你在运行 C 还是 C++ 程序? - Luchian Grigore
你如何表达 g.hexagons[0][0].vertice [0] = 0; 这行代码出现了错误?你有在GDB中检查堆栈跟踪吗?在这种情况下,你应该使用 GDB - 对吧?! - Sangeeth Saravanaraj
2个回答

5
作为一个“指向整数数组的指针数组”,要访问vertice[0],您需要执行*g.hexagons[0][0].vertice[0]
示例程序:
#include <stdio.h>

typedef struct _hexagon {
    int *vertice[6];
    int *path[6];
    int resourceType;
} hexagon;


typedef struct _game {
    hexagon hexagons[5][5];
} Game;

int main()
{
    int i1 = 1;
    int i2 = 2;
    int i3 = 3;
    int i4 = 4;
    int i5 = 5;
    int i6 = 6;

    Game g;
    g.hexagons[0][0].vertice[0] = &i1;
    g.hexagons[0][0].vertice[1] = &i2;
    g.hexagons[0][0].vertice[2] = &i3;
    g.hexagons[0][0].vertice[3] = &i4;
    g.hexagons[0][0].vertice[4] = &i5;
    g.hexagons[0][0].vertice[5] = &i6;

    printf("%d \n", *g.hexagons[0][0].vertice[0]);
    printf("%d \n", *g.hexagons[0][0].vertice[1]);
    printf("%d \n", *g.hexagons[0][0].vertice[2]);
    printf("%d \n", *g.hexagons[0][0].vertice[3]);
    printf("%d \n", *g.hexagons[0][0].vertice[4]);
    printf("%d \n", *g.hexagons[0][0].vertice[5]);

    return 0;   
}

输出:

$ gcc -Wall -ggdb test.c 
$ ./a.out 
1 
2 
3 
4 
5 
6 
$ 

希望能帮到您!
更新:根据Luchian Grigore的指出,以下小程序解释了分段错误的原因。简而言之,您正在取消引用空指针。
#include <stdio.h>

/*
int *ip[3];
+----+----+----+
|    |    |    |
+----+----+----+
   |    |    |
   |    |    +----- points to an int *
   |    +---------- points to an int *
   +--------------- points to an int *

ip[0] = 0;
ip[1] = 0;
ip[2] = 0;

+----+----+----+
|    |    |    |
+----+----+----+
   |    |    |
   |    |    +----- NULL
   |    +---------- NULL
   +--------------- NULL

*ip[0] -> dereferencing a NULL pointer ---> segmantation fault
*/

int main()
{
    int * ip[3];
    ip[0] = 0;
    ip[1] = 0;
    ip[2] = 0;

    if (ip[0] == NULL) {
        printf("ip[0] is NULL \n");
    }

    printf("%d \n", *ip[0]);
    return 0;
}

现在您可以将 int *ip[] 与您的 g.hexagons [0] [0] .vertice [0] 相关联。

为什么 g.hexagons[0][0].vertice[0] = 0; 失败了? - Luchian Grigore
你还漏了一些括号。你写的是 *g.hexagons[0][0].vertice[0],但我认为你的意思是 (*g.hexagons[0][0].vertice)[0] - efrey
他没有那个,他的代码在 g.hexagons[0][0].vertice[0] = 0; 处崩溃了,实际上相当于你的示例中的 ip[0] = 0; - Luchian Grigore
感谢您的帮助,您添加的解释特别有见地。 - Lobe

0

我认为你可能误解了在_hexagon中声明的内容。 *vertice[6]和其他数组成员都是指针数组,因此您必须像处理指针一样处理每个元素。

int x = 10;
g.hexagons[0][0].vertice[0] = &x;

x的地址存储到指针数组的位置0中的指针中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接