2014-10-11 17 views
0

我有这样的结构:初始化

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 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 

通常应该是:

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 

你能帮我吗?

+2

'graphe g = {m [5] [5],5};''m [5] [5]'这里只是一个超出界限的访问。 – dyp 2014-10-11 23:03:39

+0

C和C++都不允许直接复制整个数组。此外,通过'= {..}'初始化允许省略大括号来初始化数组/结构成员。正如它目前所写,你只用'= {m [5] [5],5}初始化'mat'成员的前两个元素;' – dyp 2014-10-11 23:07:44

回答

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)); 
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); 

要小心,因为你必须表明你数组的大小,让你拥有为此使用memcpy。

+0

谢谢它的工作,但结果它不是真的我不知道为什么? {0,1,1,1,0},{0,1,0,1,1},{1,0,1,1,0},{0,1,1,1,1},{1 ,1,0,0,1} – 2014-10-12 00:17:16

+0

您能否提供您使用的c代码! – 2014-10-12 00:21:59

+0

@Anis_Stack我可以问你,除了复制粘贴我的示例之前1小时发布的内容外,你还提供了哪些其他信息? – 4pie0 2014-10-12 01:14:33

0

graphe.mat在结构中是25(可能它必须至少25个)保留内存字节。但是m是指向另一个内存位置的指针。 C和C++都不允许将m分配给结构的成员。

如果您必须将数据复制到结构中,则必须使用memcpy和朋友。在复制字符串的情况下,您也需要处理'\0'终止符。使用数组时,2D是不是一个简单的做作喜欢简单的变量(如g.res)

#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

+0

它的工作原理但结果并非如此:{0,1, 1,1,0},{0,1,0,1,1},{1,0,1,1,0},{0,1,1,1,1},{1,1,0, 0,1}我不知道为什么? – 2014-10-11 23:50:43

+0

@SamiLi http://coliru.stacked-crooked.com/a/8550ca8e8b065144 – 4pie0 2014-10-11 23:55:07

+0

@SamiLi只是复制粘贴示例,如果你找不到错误或请粘贴完整的代码,你执行 – 4pie0 2014-10-12 01:17:54