Access to pointers within a structure

Currently I have the following code:

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


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

and basically I have:

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

This compiles, but gives a segmentation error. I tried many options like

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

which does not compile. How to access pointer memory inside a structure?

+3
source share
3 answers

Since verticeis array-of-pointes-to-integers, to access vertice[0]you need to do*g.hexagons[0][0].vertice[0]

Program Example:

#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;   
}

Conclusion:

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

Hope this helps!


UPDATE: as pointed out by Lucian Grigore

The reason for the segmentation error is explained by the following small program. In short, you are removing the NULL pointer.

#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;
}

Now you can connect int *ip[]with yourg.hexagons[0][0].vertice[0]

+5
source

, , , , _hexagon. *vertice[6], - , , .

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

x 0 .

0

you can change the following

int *vertice[6];
int *path[6];

to

int vertice[6];
int path[6];

Then it should work.

-1
source

All Articles