简体   繁体   中英

Initialization of variables matrix in a structure C

I have this struct:

typedef struct { int mat[x][x]; int res; } graphe;
graphe g;

the problem that I can't access to the graph matrix

for example when I set :

int m[5][5]={{0,1,1,1,0},{1,0,1,1,0},{1,1,0,1,1},{1,1,1,0,1},{0,0,1,1,0}};
graphe g = { m[5][5], 5};

for(i=0;i<lignes;i++)
    {
        for(j=0;j<lignes;j++)
        {
            printf("%i ",g.mat[i][j]);
        }
        printf("\n");
    }
printf("Res = %i ",g.res);

I have

0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Res =0

Normally should be:

0 1 1 1 0
1 0 1 1 0
1 1 0 1 1
1 1 1 0 1
0 0 1 1 0
Res =5

Can you help me?

graphe.mat is 25 (probably, it has to be at least 25 in this case) bytes of reserved memory inside the struct. But m is a pointer to another memory location. Neither C nor C++ allow to assign m to the struct's member.

If you have to copy data into the struct you have to use memcpy and friends. In case of copying the strings you need to handle the '\\0' terminator too.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct { int mat[5][5]; int res; } graphe;

int main(void) {
int m[5][5]={{0,1,1,1,0},{1,0,1,1,0},{1,1,0,1,1},{1,1,1,0,1},{0,0,1,1,0}};
graphe g;
memcpy( g.mat, m, sizeof(m));

example

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct { int mat[5][5]; int res; } graphe;

int main(void) {
int m[5][5]={{0,1,1,1,0},{1,0,1,1,0},{1,1,0,1,1},{1,1,1,0,1},{0,0,1,1,0}};
graphe g;
memcpy( g.mat, m, sizeof(m));
g.res= 5;
for(i=0;i<lignes;i++)
    {
        for(j=0;j<lignes;j++)
        {
            printf("%i ",g.mat[i][j]);
        }
        printf("\n");
    }
printf("Res = %i ",g.res);

be careful when using array 2D is not a simple affectation like simple variable (like g.res), because you have to indicate the size of your array, so you have to use memcpy for that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM