>我在软件开发方面有 20 多年的经验,但我在一个简单的 C 程序中遇到了一个非常不寻常的错误,我将在针对初级或初学者开发人员的博客文章中使用。
我的 C 程序构建一个基于一个整数的结构的链表,并尝试构建一个包含 100,000 个节点的链表。它使用插入函数,FOR循环调用插入函数,当for循环迭代10,000次时,该程序工作正常,但是程序在尝试迭代100,000次时没有生成任何输出,多么奇怪!
在Windows 10上的Visual Studio中运行此程序时,以及在使用gcc编译并在OpenBSD Unix上运行时,我遇到了相同的问题。
这是我的代码:
#include <stdio.h>
// struct type for linked list
struct Integers
{
unsigned int nIntNumber;
struct Integers* next;
struct Integers* previous;
};
// head and last nodes
struct Integers* head = NULL;
struct Integers* last = NULL;
// to keep track of the current node pointed to
struct Integers* current = NULL;
// Create Linked List
void insert(int data) {
// Allocate memory for new node
struct Integers* node = (struct Integers*) malloc(sizeof(struct Integers));
node->nIntNumber = data;
node->previous = NULL;
node->next = NULL;
// If head is empty, create new list
if (head == NULL) {
head = node;
return;
}
current = head;
// move to the end of the list
while (current->next != NULL)
current = current->next;
// Insert link at the end of the list
current->next = node;
last = node;
node->previous = current;
}
// output the list
void outputList() {
// start at first node in list
struct Integers* ptr = head;
// output the contents of the list
while (ptr->next != NULL) {
printf("%d n", ptr->nIntNumber);
ptr = ptr->next;
}
}
int main()
{
// loop through total number of elements adding each integer with each iteration
for (int i = 0; i < 100000; i++)
{
insert(i);
}
// output the contents of the list
outputList();
// debug
unsigned int testInt = 0;
printf("Max Int: %u", --testInt);
return 0;
}
如果您有last
请不要每次都迭代以查找最后一个节点。循环也不正确
void insert(int data) {
// Allocate memory for new node
struct Integers* node = malloc(sizeof(*node));
if(!node) return;
node->nIntNumber = data;
node->next = NULL;
// If head is empty, create new list
if (head == NULL) {
head = node;
last = node;
node->previous = NULL;
}
else
{
last -> next = node;
node -> previous = last;
last = node;
}
}
// output the list
void outputList() {
// start at first node in list
struct Integers* ptr = head;
// output the contents of the list
while (ptr != NULL) {
printf("%d n", ptr->nIntNumber);
ptr = ptr->next;
}
}
在VS for Windows中,您需要设置Compile as C
选项。否则,它将被编译为C++程序。