首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

关于结构体指针的一个有关问题~

2012-02-20 
关于结构体指针的一个问题~~~#includestdio.htypedef struct{int b[4]}graphmain(){graph *aint x[4]

关于结构体指针的一个问题~~~
#include<stdio.h>
typedef struct
{
int b[4];
}graph;
main()
{
graph *a;
int x[4]={1,2,3,4};
int i;
a->b[2]=x[0];
printf("%d",a->b[2]);
getchar();
}



#include<stdio.h>
#include<malloc.h>
typedef struct
{
int *b;
}graph;
main()
{
graph *a;
int x[4]={1,2,3,4};
int i;
a->b=(int *)malloc(4*sizeof(int));
a->b[2]=x[0];
printf("%d",a->b[2]);
getchar();
}

为什么这两个调试成功,却都不能运行呢?应该怎么赋值才能得到正确答案?在不改变结构体,还有定义的情况下?

[解决办法]
graph *a = (graph*)malloc(sizeof(graph));
[解决办法]
调试成功是偶然的,都是对野指针的操作,很不安全,可以试试下面的方法

C/C++ code
#include<stdio.h>typedef struct{    int b[4];}graph;int main(int argc,char *argv[]){    graph a;    int x[4]={1,2,3,4};    int i;    a.b[2]=x[0];    printf("%d",a.b[2]);    getchar();    return 0;} 

热点排行