//sample code 1
#include <stdio.h>
#define LEN 41
struct book {
char title[LEN];
char author[LEN];
}
int main() {
struct book *b; //有意义的指针
printf("Enter the book title: ");
scanf("%40s", b->title);
printf("Enter the book author: ");
scanf("%40s", b->author);
return 0;
}
//sample code 2
#include <stdio.h>
#define LEN 41
struct book {
char title[LEN];
char author[LEN];
}
struct book *newBook();
int main() {
struct book *b;//有意义的指针
b = newBook();
return 0;
}
struct book *newBook() {
struct book *temp;//NULL指针,为何?
printf("Enter the book title: ");
scanf("%40s", temp->title);
printf("Enter the book author: ");
scanf("%40s", temp->author);
return temp;
}
为什么上面两段代码,第一段可以跑,第二段在跑newBook()
的时候就会报Segmentation fault..后来我在第二段代码中用struct book *temp = (struct book *)malloc(sizeof(struct book));
之后第二段就不会报错了。。就有个疑问了。在第一段代码main中定义的book结构指针。这个指针是个有意义的指针。但是到了第二段代码的newBook
方法中定义的话,就会是NULL
指针。。求解。
第一段程序你结构体指针没初始化, b根本就是的野指针嘛, 你程序能运行时因为野指针恰好没影响到程序的运行;
第二段函数中返回结构体指针, main函数若是处理该给指针就属于越界操作.
你通过malloc创建结构体, 会在内存中段空间就开辟了这段内存. 只要你没有free 这段内存就会一直存在, 因此在mian中访问该指针是合法的.