首页 > C语言声明结构的指针的问题。

C语言声明结构的指针的问题。

//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指针。。求解。


第一段和第二段都没有对指针做任务初始化,都是不对的。
正确的作法:第一段改成
struct book *b = NULL;
b = (struct book *)malloc(sizeof(struct book));


赞同 @ge4los
指向任何类型变量的指针,只声明不初始化都是野指针。


第一段程序你结构体指针没初始化, b根本就是的野指针嘛, 你程序能运行时因为野指针恰好没影响到程序的运行;

第二段函数中返回结构体指针, main函数若是处理该给指针就属于越界操作.
你通过malloc创建结构体, 会在内存中段空间就开辟了这段内存. 只要你没有free 这段内存就会一直存在, 因此在mian中访问该指针是合法的.

【热门文章】
【热门文章】