c语言结构体指针初始化

     今天终于看完了C语言深度剖析这本书,对C语言有了进一步的了解与感悟,突然发觉原来自己学C语言的时候学得是那样的迷糊,缺少深入的思考,在重新看书的时候发觉C语言基本教材虽然经典,但是缺乏独到性,老师在讲解的过程中也就照本宣科了,没有多大的启迪。

     看到C语言内存管理这块,发觉还是挺有用的,当然平时在编程时基本上就没有考虑过内存问题。

     定义了指针变量,没有为指针分配内存,即指针没有在内存中指向一块合法的内存,尤其是结构体成员指针未初始化,往往导致运行时提示内存错误。

#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;
}

由于结构体成员指针未初始化,因此在运行时提示内存错误

#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;   
}  

同时也可能出现没有给结构体指针分配足够的空间

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

 

posted on 2014-03-25 20:27  FreedomQQkiko  阅读(5499)  评论(0编辑  收藏  举报

导航