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字节的内存编译器

相关文章
相关标签/搜索