标签:
结构体成员指针初始化
不可以正确运行的初始化方式(1):
#include <stdio.h> #include <string.h> #include <malloc.h> //#include "a.h" //char a[100]; struct stu { char* name; int num; }*pst,st; void init_pst() { pst = (struct stu *)malloc(sizeof(struct stu)); //pst->name = (char*)malloc(sizeof(char*)); //pst->num = 0; } void free_pst() { free(pst); } int main(void) { //strcpy(pst->name,"Jacy"); //pst->num = 99; init_pst(); //test(); strcpy(pst->name,"Jacy"); pst->num = 99; printf("%s %c",pst->name,pst->num); free_pst(); return 0; }
#include <stdio.h> #include <string.h> #include <malloc.h> //#include "a.h" //char a[100]; struct stu { char* name; int num; }*pst,st; void init_pst() { NULL; //pst = (struct stu *)malloc(sizeof(struct stu)); //pst->name = (char*)malloc(sizeof(char*)); //pst->num = 0; } void free_pst() { free(pst); } int main(void) { //strcpy(pst->name,"Jacy"); //pst->num = 99; init_pst(); //test(); strcpy(pst->name,"Jacy"); pst->num = 99; printf("%s %c",pst->name,pst->num); free_pst(); return 0; }
可以正确运行的初始化方式:
#include <stdio.h> #include <string.h> #include <malloc.h> //#include "a.h" //char a[100]; struct stu { char* name; int num; }*pst,st; void init_pst() { pst = (struct stu *)malloc(sizeof(struct stu)); pst->name = (char*)malloc(sizeof(char*)); pst->num = 0; } void free_pst() { free(pst); } int main(void) { //strcpy(pst->name,"Jacy"); //pst->num = 99; init_pst(); //test(); strcpy(pst->name,"Jacy"); pst->num = 99; printf("%s %c",pst->name,pst->num); free_pst(); return 0; }
以后的编程习惯:结构体一定义,立马进行初始化内存分配。
标签:
原文地址:http://blog.csdn.net/oimchuan/article/details/44035137