为什么这个c程序片断编译通过,但一运行就内存读写错误?

来源:百度知道 编辑:UC知道 时间:2024/06/30 15:52:41
我是vc6.0写的
大家帮我看下为什么一运行就出现内存错误,这个程序我是想看下a输出后是什么东西
#include <stdio.h>
#include <string.h>
#include <conio.h>

struct Node{
char a[4];
char b[4];
};

main(){
struct Node *node = NULL;
char ie[4] = "he";

node->a[0] = 'a';
node->a[1] = 'a';
node->a[2] = 'a';
node->a[3] = 'a';

strcpy( node->b, ie );

printf("%s",node->a);
getch();
}

你定义的结构体指针没有分配空间,不能进行赋值操作。
你可以用动态分配,也可以简单的静态分配。
这里给出一个静态分配的例子
main(){
struct Node node0, *node = &node0;
......
}

没有分配内存,改成这样可以了
#include <stdio.h>
#include <string.h>
#include<stdlib.h>
#include <conio.h>

struct Node{
char a[4];
char b[4];
};

main(){
struct Node *node = NULL;
node=(Node *)malloc(sizeof(Node));
char ie[4] = "he";

node->a[0] = 'a';
node->a[1] = 'a';
node->a[2] = 'a';
node->a[3] = 'a';

strcpy( node->b, ie );

printf("%s",node->a);
getch();
}