【发布时间】:2015-04-12 00:51:56
【问题描述】:
似乎我的程序在打印两个姓氏时都崩溃了,我不明白为什么这个链接列表会在打印两个姓氏时崩溃。希望有任何帮助:((。我正在实现一个包含多个元素的链接列表,但是我只是打印了姓氏以查看列表是否会正确迭代,结果证明它在打印第二个姓氏“程序员”后崩溃。
struct user
{
char email[30];
char lastname[30];
char firstname[30];
char phonenumber[20];
char status [50];
char password [50];
};
struct nodeTag {
struct user data;
struct nodeTag *pNext;
struct nodeTag *pPrev;
};
typedef struct nodeTag nodeStructType;
int main(){
nodeStructType *pFirst;
nodeStructType *pSecond;
nodeStructType *pRun;
pFirst = malloc(sizeof(nodeStructType));
strcpy(pFirst->data.email,"art@yahoo.com");
strcpy(pFirst->data.password,"artist");
strcpy(pFirst->data.lastname,"iamaartist");
strcpy(pFirst->data.firstname,"artist");
strcpy(pFirst->data.status,"Hello i am a artist");
strcpy(pFirst->data.phonenumber,"092712345678");
pSecond= malloc(sizeof(nodeStructType));
pFirst->pNext=pSecond;
strcpy(pSecond->data.email,"programming@yahoo.com");
strcpy(pSecond->data.password,"programmer");
strcpy(pSecond->data.lastname,"programmer");
strcpy(pSecond->data.firstname,"programmer");
strcpy(pSecond->data.status,"Hello i am a programmer");
strcpy(pSecond->data.phonenumber,"092712345678");
pRun=pFirst;
while(pRun->pNext!=NULL){
printf("%s\n", pRun->data.lastname);
pRun=pRun->pNext;
}
}
【问题讨论】:
-
分配
pSecond后需要设置pSecond->pNext = NULL。否则,while可能会在它不为零时尝试使用它。 -
另外,
nodeStructType是什么?这不在您发布的代码中。 -
这是一个 typedef 抱歉。
标签: c linked-list