單純的紀錄之前所犯的錯,在struct裡面宣告了char *,結果只有重新malloc struct,卻沒注意到char *的問題。
在struct中的char *,如果沒有每次重新malloc記憶體空間,僅會用4 bytes來紀錄address,所以每個宣告出來的struct都會使用到同一個記憶體空間的char *。
底下是個簡單的使用struct來建立的link list範例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 80
typedef struct _info{
int id;
char *name;
_info * Next;
}student_info;
typedef student_info * Info;
int _tmain(int argc, _TCHAR* argv[])
{
Info Head, New, Point, Temp;
char *str;
int i;
str = (char *)malloc(sizeof(char) * SIZE);
for(i = 1; i < 4; i++){
printf("Please input a string: ");
scanf("%s", str);
if(i == 1){
Head = (Info)malloc(sizeof(student_info));
Head->id = i;
//Head->name = str; //錯誤示範
Head->name = (char *)malloc(sizeof(char) * (strlen(str) + 1)); //正確作法
strcpy(Head->name, str);
Head->Next = NULL;
Point = Head;
}else{
New = (Info)malloc(sizeof(student_info));
New->id = i;
//New->name = str; //錯誤示範
New->name = (char *)malloc(sizeof(char) * (strlen(str) + 1)); //正確作法
strcpy(New->name, str);
New->Next = NULL;
Point->Next = New;
Point = New;
}
}
Point = Head;
while(1){
printf("ID = %d, Name = %s\n", Point->id, Point->name);
if(Point->Next == NULL){
free(Point);
break;
}else{
Temp = Point->Next;
free(Point);
Point = Temp;
}
}
return 0;
}
留言列表