2017-11-24 12 views
0

リストの最後にデータを挿入しようとしていますが、動作していません。実行時に例外が発生します。このコードでリンクリストに問題がありますが、デバッガはテンポラリメモリにアクセスできません。

struct gradeNode *newNode = (struct gradeNode*)malloc(sizeof(struct gradeNode)); 
assert(newNode != NULL); 

strcpy(newNode->courseName, courseName); // copying the course name 
newNode->next = NULL; 

struct gradeNode *temp = students[i].gradelist->head; // a temp 

// here is the problem: the debugger says ecxeption, can't access memory 
while (temp->next != NULL) 
{ 
    temp = temp->next; // I can't get to here 
    temp->next = newNode; 
} 
+2

[malloc()の返り値をCでキャストしない理由についてのこのディスカッションを参照してください。](https://stackoverflow.com/q/605845/2173917) –

+1

'students [i]です。 gradelist-> head'を正しく初期化しましたか?これはいつ起こるのですか? 'temp'はヌルか無効なポインタですか? [最小限の、完全で検証可能な例](http://stackoverflow.com/help/mcve)を作成してください。そして、[良い質問をする方法を読む](http://stackoverflow.com/help/how-to-ask)に時間を割けてください。 –

+1

@loay tempはNULLに等しいと思われます。 –

答えて

0

データメンバheadが正しく初期化またはNULLに等しいされていないか

struct gradeNode *temp = students[i].gradelist->head;//a temp 
    while (temp->next != NULL)// 

をスニペット。どちらの場合も、式temp->nextは未定義の動作になります。

while (temp->next != NULL) 
{ 
    temp = temp->next; // I can't get to here 
    temp->next = newNode; 
} 

(あなたのコードを編集した後に)

そして、このループは意味がありません。あなたが意味するようです

while (temp->next != NULL) 
{ 
    temp = temp->next; // I can't get to here 
} 
temp->next = newNode; 

いずれの場合も、使用されている方法が間違っています。

代わりに、次の

struct gradeNode **temp = &students[i].gradelist->head;//a temp 
    while (*temp) temp = &(*temp)->next; 

    *temp = newNode; 

を試してみてください、片側一重リンクリストを持っていると、リストの末尾にデータを追加しようとする論理的に矛盾していることを考慮してください。単一リンクリストにデータを追加する場合は、リストを両面リンクリストとして定義する必要があります。

+0

iam申し訳ありません私は新しいことを覚えていますので、私のコードはちょっと寂しいですが、私のコードはcodeblocksで動作しますが、visualstudioここで '\t struct gradeNode * temp = students [i] .gradelist-> head; \t \t \t while(temp-> next!= NULL) \t \t \t {'** struct stud { \t int id; \t float grade平均; \t float incomeAverage; \t struct gradeList * gradelist; \t struct incomeList * incomelist; }; typedef struct Stud Students; \t int等級; \t struct gradeNode * next; \t struct gradeNode * prev; }; ** – loay

+0

@loay関数の実装方法を私の答えで示しました。 –

関連する問題