【发布时间】:2010-09-25 03:18:04
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/*Define custom functions */
void insertElement();
bool elementExists();
int getNumElements();
/*Create linked list */
struct node {
int number;
int occurence;
struct node *next;
};
/*Call our linked list freqTable */
struct node *freqTable = NULL;
unsigned int numElements = 0;
int main(){
int readNumElements = 0;
int i = 0;
int newNum, status;
status = scanf("%d", &readNumElements);
if(status == -1){
fprintf(stderr, "%d is not a number\n", readNumElements);
exit(-1);
}
for (i = 0; i < readNumElements;i++) {
status = scanf("%d", &newNum);
if(status == -1){
fprintf(stderr, "%d is not a number\n", newNum);
exit(-1);
}
if(elementExists(newNum)){
printf("%d exists\n", newNum);
}else{
insertElement(&freqTable, newNum);
}
}
return 0;
}
void insertElement(struct node **list, int n){
struct node *new_input;
new_input = malloc(sizeof(struct node));
if(new_input == NULL){
fprintf(stderr,"Error: Failed to create memory for new node\n");
exit(EXIT_FAILURE);
}
new_input->number = n;
new_input->occurence = 1;
new_input->next = *list;
numElements++;
*list = new_input;
}
bool elementExists(int n){
printf("%d\n", freqTable->number);
return false;
}
int getNumElements(){
return numElements;
}
好的,这就是我得到的。这应该可以编译。
问题来了
if(elementExists(newNum)){
printf("%d exists\n", newNum);
}else{
insertElement(&freqTable, newNum);
}
我得到分段错误,我不知道为什么。
【问题讨论】:
-
剩下的代码在哪里?
-
如果您从不分配节点并将其分配给
freqTable变量,您将始终访问内存位置 0 + 一些偏移量,从而保证分段错误! -
我建议您发布最短的代码,应该编译和工作但会产生错误。
-
我认为您在此过程中删除了问题。
-
@Matt:如果你的问题得到了解决,你不需要删除程序 :) 我已经回滚了更改。
标签: c search linked-list