以下代码在 fscanf 的 for 循环的第二次迭代中给我一个段错误,可能是什么问题??? fflush(stdin) 在这里使用正确吗???或者还有其他原因。 该代码应该创建一个 NODE 类型的数组,每个索引包含一个链表,其中包含从 file.txt 读取的 32 个整数节点
FILE *file = fopen ("file.txt", "r");
int count =0;
int x=0;
for ( x=0; x<=312500; x++)
{
while (count <=32)
{
fscanf (file, "%d", &temp->num);
temp->ptr=NULL;
newNode = (NODE *)malloc(sizeof(NODE));
newNode->num=temp->num;
newNode->ptr=NULL;
if (first != 0)
{
last->ptr=newNode;
last=newNode;
count=count+1;
}
else
{
first = newNode;
last = newNode;
count=count+1;
}
fflush(stdin);
}
count =0;
array[x] = (NODE*) malloc(sizeof(NODE));
array[x]->ptr=first;
first->ptr=0;
first=NULL;
last->ptr=0;
last=NULL;
temp->ptr = 0;
temp=NULL;
fflush(stdin);
}
fclose (file);
最佳答案
循环的第一次迭代通过设置结束
temp=NULL;
您在内部第二次迭代开始时取消引用 NULL
fscanf (file, "%d", &temp->num);
您的代码没有显示 temp
是如何分配的,因此很难说您是应该停止将其设为 NULL 还是分配一个新实例。
关于c - fscanf 上的段错误(核心已转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19996152/