我有一个关于C编程中链表的问题。我写了这段代码,但在尝试运行代码时出现了运行时错误。我是C编程的新手,请帮忙。
- Project1.exe中0x00161A66处引发异常:0xC0000005:写入位置0xCCCCCCEC时发生访问冲突
- Project1.exe中0x00161A66处未处理的异常:0xC0000005:写入位置0xCCCCCCEC时发生访问冲突。Insert Thompson发生错误
以下是我正在努力解决的问题。我无法按字母顺序打印出来。
我正在做的问题是
a) Create a pointer to the start of the list called startPtr. The list is empty.
b) Create a new node of type GradeNode that’s pointed to by pointer newPtr of type GradeNodePtr.
Assign the string "Jones" to member lastName and the value 91.5 to member
grade (use strcpy). Provide any necessary declarations and statements.
c) Assume that the list pointed to by startPtr currently consists of 2 nodes—one containing
"Jones" and one containing "Smith". The nodes are in alphabetical order. Provide
the statements necessary to insert in order nodes containing the following data for
lastName and grade:
"Adams" 85.0
"Thompson" 73.5
"Pritchard" 66.5
这是代码:
#include <stdio.h>
#include <string.h>
int main(){
struct gradeNode{
char lastName [20];
double grade;
struct gradeNode *nextPtr;
};
typedef struct gradeNode GradeNode;
typedef GradeNode *GradeNodePtr;
GradeNodePtr startPtr = NULL;
GradeNodePtr currentPtr = NULL;
GradeNodePtr previousPtr = NULL;
GradeNodePtr newPtr;
if (newPtr != NULL){
newPtr = malloc(sizeof(GradeNode));
strcpy(newPtr -> lastName,"Jones");
newPtr -> grade = 91.5;
newPtr -> nextPtr = NULL;
}
//Insert "Adams"
//previousPtr is NULL, and currentPtr points to the first node in the list.
newPtr -> nextPtr = currentPtr;
startPtr = newPtr;
newPtr = malloc(sizeof(GradeNode));
strcpy(newPtr -> lastName,"Smith");
newPtr -> grade = 40.5;
newPtr -> nextPtr = NULL;
newPtr -> nextPtr = currentPtr;
startPtr = newPtr;
newPtr = malloc(sizeof(GradeNode));
strcpy(newPtr -> lastName,"Adams");
newPtr -> grade = 85.0;
//Insert "Thompson"
//previousPtr points to the last node in the list(containing Smith") and currentPtr is NULL
newPtr -> nextPtr = currentPtr; //or newPtr -> nextPtr = NULL
previousPtr -> nextPtr = newPtr;
newPtr = malloc(sizeof(GradeNode));
strcpy(newPtr -> lastName,"Thompson");
newPtr -> grade = 73.5;
//Insert "Pritchard"
//previousPtr points to the node containing "Jones" and currentPtr points to the node contaiing "Smith"
newPtr -> nextPtr = currentPtr;
previousPtr -> nextPtr = newPtr;
newPtr = malloc(sizeof(GradeNode));
strcpy(newPtr -> lastName,"Pritchard");
newPtr -> grade = 66.5;
currentPtr = startPtr;
while(currentPtr!=NULL){
printf("Lastname = %snGrade = %.1fnn",currentPtr->lastName,currentPtr->grade);
currentPtr = currentPtr->nextPtr;
}
}
首先,您应该明确您的逻辑
这里有一些你可以使用的技巧。
- 您不包括
stdlib.h
,它包括malloc
的定义。在这种情况下,编译器将发出一条警告消息 - 在创建
newPtr
之后,您正在检查NULL
。它最初将是NULL
或一些垃圾值。只有当内存不是NULL
时才分配内存,这是不正确的 - 您没有正确链接节点。首先在一篇论文中阐述你的逻辑,然后尝试对其进行编码