c語言結構體指針初始化

     今天終於看完了C語言深度剖析這本書,對C語言有了進一步的瞭解與感悟,忽然發覺原來本身學C語言的時候學得是那樣的迷糊,缺乏深刻的思考,在從新看書的時候發覺C語言基本教材雖然經典,可是缺少獨到性,老師在講解的過程當中也就照本宣科了,沒有多大的啓迪。編程

     看到C語言內存管理這塊,發覺仍是挺有用的,固然平時在編程時基本上就沒有考慮過內存問題。spa

     定義了指針變量,沒有爲指針分配內存,即指針沒有在內存中指向一塊合法的內存,尤爲是結構體成員指針未初始化,每每致使運行時提示內存錯誤。指針

#include "stdio.h"
#include "string.h"

struct student
{
       char *name;
       int score;
       struct student *next;      
}stu, *stul;

int main()
{
       strcpy(stu.name,"Jimy");   
       stu.score = 99;  
       return 0;
}

因爲結構體成員指針未初始化,所以在運行時提示內存錯誤code

#include   「stdio.h」 
#include   "malloc.h"
#include   "string.h"
  
struct student
{   
    char *name;   
    int score;   
    struct student* next;   
}stu,*stu1;    
  
int main()
{    
    stu.name = (char*)malloc(sizeof(char)); /*1.結構體成員指針須要初始化*/  
    strcpy(stu.name,"Jimy");   
    stu.score = 99;   
    
    stu1 = (struct student*)malloc(sizeof(struct student));/*2.結構體指針須要初始化*/  
    stu1->name = (char*)malloc(sizeof(char));/*3.結構體指針的成員指針一樣須要初始化*/  
    stu.next  = stu1;   
    strcpy(stu1->name,"Lucy");   
    stu1->score = 98;   
    stu1->next = NULL;   
    printf("name %s, score %d \n ",stu.name, stu.score);   
    printf("name %s, score %d \n ",stu1->name, stu1->score);   
    free(stu1);   
    return 0;   
}  

同時也可能出現沒有給結構體指針分配足夠的空間blog

    stu1 = (struct student*)malloc(sizeof(struct student));/*2.結構體指針須要初始化*/ 

如本條語句中每每會有人寫成內存

    stu1 = (struct student*)malloc(sizeof(struct student *));/*2.結構體指針須要初始化*/ 

這樣將會致使stu1的內存不足,由於sizeof(struct student)的長度爲8,而sizeof(struct student *)的長度爲4,在32位系統中,編譯器默認會給指針分配4字節的內存編譯器

相關文章
相關標籤/搜索