[英]Accessing pointers within a struct
目前我有以下代码:
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;
哪个不编译。 如何从结构中访问指针的内存?
由于vertice
是一个array-of-pointes-to-integers
,要访问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所指出的那样
下面的小程序解释了分段错误的原因。 简而言之,您将取消引用NULL指针。
#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]
我想你可能误解了你在_hexagon
声明的_hexagon
。 *vertice[6]
和你的其他数组成员都是指针数组 ,所以你必须像控制指针一样对待每个元素。
int x = 10;
g.hexagons[0][0].vertice[0] = &x;
将x
的地址存储到指针数组的第0位指针。
您可能想要更改以下内容
int *vertice[6];
int *path[6];
至
int vertice[6];
int path[6];
然后它应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.