[問題] C的連結串列 這樣寫引起存取違規
遇到的問題:設定連結串列 依序印出
希望得到的正確結果: g-->o-->o-->d-->NULL
n-->i-->g-->h-->t-->NULL
程式跑出來的錯誤結果: 存取違規
開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux)
dev-c++的C
有問題的code: (請善用置底文標色功能)
#include <stdio.h>
#include <stdlib.h>
struct charnode {
char data;
struct charnode *nextPtr;
};
typedef struct charnode CharNode;
typedef CharNode *CharNodePtr;
void creat(CharNodePtr nPtr1,CharNodePtr nPtr2);
void printLinkedList(CharNodePtr nPtr);
//***********************************************************************************
int main()
{
CharNodePtr startptr1 = malloc(sizeof(CharNode));
CharNodePtr startptr2 = malloc(sizeof(CharNode));
creat(startptr1,startptr2);
printf("The first linked list\n");
printLinkedList(startptr1);
printf("The second linked list\n");
printLinkedList(startptr2);
system("PAUSE");
return 0;
}
//***********************************************************************************
void creat(CharNodePtr nPtr1,CharNodePtr nPtr2){
char list1[]="good";
char list2[]="night";
int i;
for(i=0;list1[i]!='\0';i++){
nPtr1->data = list1[i];
nPtr1->nextPtr = malloc(sizeof(CharNode));
nPtr1 = nPtr1->nextPtr;
}
nPtr1=NULL;
for(i=0;list2[i]!='\0';i++){
nPtr2->data = list2[i];
nPtr2->nextPtr = malloc(sizeof(CharNode));
nPtr2 = nPtr2->nextPtr;
}
nPtr2=NULL;
}
//***********************************************************************************
void printLinkedList(CharNodePtr currentPtr)
{
while(currentPtr != NULL){
printf("%c -->",currentPtr->data);
currentPtr = currentPtr->nextPtr;
}
printf("NULL\n\n");
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.106.167
推
05/31 19:27, , 1F
05/31 19:27, 1F
推
06/01 10:31, , 2F
06/01 10:31, 2F
推
06/01 10:34, , 3F
06/01 10:34, 3F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章