关于结构体指针的一个问题~~~
#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;}