C结构中变量矩阵的初始化

C结构中变量矩阵的初始化,c,struct,C,Struct,我有这个结构: typedef struct { int mat[x][x]; int res; } graphe; graphe g; 我无法访问图形矩阵的问题 例如,当我设置: 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<lign

我有这个结构:

typedef struct { int mat[x][x]; int res; } graphe;
graphe g;
我无法访问图形矩阵的问题

例如,当我设置:

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);
通常应为:

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
您能帮助我吗?

graph.mat是结构中25字节的保留内存(在这种情况下,它可能至少必须是25字节)。但是
m
是指向另一个内存位置的指针。C和C++都不允许将<代码> M <代码>分配给Stult的成员。

如果必须将数据复制到结构中,则必须使用
memcpy
和friends。在复制字符串的情况下,还需要处理
'\0'
终止符

#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));
#包括
#包括
#包括
typedef结构{int mat[5][5];int res;}图形;
内部主(空){
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};
图g;
memcpy(g.mat,m,sizeof(m));
#包括
#包括
#包括
typedef结构{int mat[5][5];int res;}图形;
内部主(空){
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};
图g;
memcpy(g.mat,m,sizeof(m));
g、 res=5;

对于(i=0;i代码){ m [ 5 ] [ 5 ],5 };< /COD> <代码> M [5 ] [5 ] < /COD>这里只是一个越界访问。C和C++都不允许直接复制整个数组。此外,初始化通过<代码> {{}
允许省略大括号来初始化数组/结构成员。在当前编写的过程中,您仅使用
={m[5][5],5};
初始化
mat
成员的前两个元素;它的工作方式,但结果不是真的:{0,1,1,1,1,0},{0,1,0,1},{1,1,1,1},{0,1}我不知道为什么?@SamiLi如果你找不到bug,就复制粘贴这个例子,或者请粘贴你执行的完整代码,它可以工作,但是结果不是真的,我不知道为什么{0,1,1,1,0},{0,1,0,1,1},{1,0,1,1,1},{0,1,1,0},{0,1,1,1},{1,1,0,1}@Anis_Stack我可以问你除了复制粘贴我在你之前1小时发布的示例外,你还提供了哪些其他信息吗?@0d0a我使用代码向Sami Li解释使用memcpy和使用简单矫揉造作!!
#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));
#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);