在Linux下進(jìn)行C語(yǔ)言編程時(shí),遇到一個(gè)錯(cuò)誤,網(wǎng)上說的都很復(fù)雜,看都看不懂,其實(shí)就是你對(duì)指針進(jìn)行直接操作之前,沒有對(duì)它進(jìn)行分配地址空間。
所以在運(yùn)行的時(shí)候,它不知道在那里操作(比如賦值,取值),所以才報(bào)了這個(gè)錯(cuò)誤。
在C語(yǔ)言中,定義一個(gè)指針變量時(shí),系統(tǒng)不會(huì)像在定義基本數(shù)據(jù)類型一樣自動(dòng)為指針分配地址空間的,所以我們?cè)诙x指針變量時(shí)要手動(dòng)為它分配一個(gè)地址空間

image.png
出錯(cuò)代碼
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define OVERFLOW 0
#define OK 1
#define LIST_INIT_SIZE 100
#define LISTINCREMENY 10
typedef struct{
char no[20]; //學(xué)號(hào)
char name[20]; //姓名
char sex[5]; //性別
int age; //年齡
}student;
int main()
{
student* stu=NULL;
stu->age=18;
strcpy(stu->name,"李四");
strcpy(stu->no,"20144834638");
strcpy(stu->sex,"男");
printf("name:%s, no: %s, sex: %s, age: %d",stu->name,stu->no,stu->sex,stu->age);
free(stu);
return 0;
}
解決辦法:
為指針變量分配一個(gè)地址空間,完美解決。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define OVERFLOW 0
#define OK 1
#define LIST_INIT_SIZE 100
#define LISTINCREMENY 10
typedef struct{
char no[20]; //學(xué)號(hào)
char name[20]; //姓名
char sex[5]; //性別
int age; //年齡
}student;
int main()
{
student* stu=NULL;
stu=(student *)malloc(LIST_INIT_SIZE*sizeof(student)); //為指針變量分配地址空間
stu->age=18;
strcpy(stu->name,"李四");
strcpy(stu->no,"20144834638");
strcpy(stu->sex,"男");
printf("name:%s, no: %s, sex: %s, age: %d",stu->name,stu->no,stu->sex,stu->age);
free(stu);
return 0;
}
運(yùn)行結(jié)果:已經(jīng)可以正常操作指針了

image.png