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;

これはコンパイルされません。構造体内からポインタのメモリにアクセスするにはどうすればよいですか?

4

2 に答える 2

5

のようverticearray-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]

于 2012-04-25T07:02:22.643 に答える
0

で宣言したことを誤解している可能性があると思います_hexagon*vertice[6]他の配列メンバーはすべてポインターの配列であるため、各要素をポインターのように扱う必要があります。

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

xポインターの配列の位置 0 にポインターのアドレスを格納します。

于 2012-04-25T06:59:52.083 に答える