gpt4 book ai didi

当函数打印指针数组的内容时,c 程序崩溃

转载 作者:太空宇宙 更新时间:2023-11-04 01:54:29 24 4
gpt4 key购买 nike

我正在学习 C。我编写了我的程序来从文本文件中读取数据并将其打印出来。在构建过程中编译器没有给出错误。但是,当我尝试运行该程序时,该程序崩溃了。我检查了当 printTable 函数被删除时,程序运行并打印 main() 循环中的内容。我还尝试删除变量“total”,但程序仍然崩溃。有什么问题?

#include<stdio.h>
#include<stdlib.h>

typedef struct{
char *country;
int females;
int males;
}person_count;

void printTable(person_count *data[]){
printf("Country Females Males Total\n");
int i;
int total[158];
for(i=0;i<158;i++){

total[i]=data[i]->females+data[i]->males;

printf("%15s %7i %7i %8i\n",data[i]->country,data[i]->females,data[i]->males,total[i]);
}
}


int main(){
person_count *data[158];

FILE *eduData=fopen("SecondaryEd2005.txt","r");
if(eduData==NULL){
printf("File not found.");
exit(1);
}
printf("File opened successfully.\n");

int k;
for(k=0;k<158;k++){
data[k]=malloc(sizeof(person_count));
char place[20];
fscanf(eduData,"%s %i %i\n",place,&data[k]->females,&data[k]->males);
data[k]->country=place;
printf("%s %i %i\n",data[k]->country,data[k]->females,data[k]->males);
}

printTable(data);

fclose(eduData);

return 0;
}

txt 文件内容示例:

比利时 391138 423401伯利兹 15591 15786贝宁 154266 281183百慕大 2494 2262不丹 19870 22274

最佳答案

我为你修好了程序。最重要的是让 country 成为固定长度的字符数组,而不是指针。此外,请确保释放分配给程序的所有内存,否则会产生内存泄漏。

#include <stdio.h>
#include <stdlib.h>

typedef struct{
char country[20]; //fixed to reflect country field better
int females;
int males;
}person_count;

void printTable(person_count *data[],int items){
items++;
int i,total[items]; //replaced fixed value with variable to prevent excessive empty rows from printing
printf("Country Females Males Total\n");
for(i=0;i<items;i++){
total[i]=data[i]->females+data[i]->males;
printf("%15s %7i %7i %8i\n",data[i]->country,data[i]->females,data[i]->males,total[i]);
}
}


int main(){

FILE *eduData=fopen("SecondaryEd2005.txt","r");
if(eduData==NULL){
printf("File not found.");
exit(1);
}
printf("File opened successfully.\n");

int k,fscanret;
person_count* data[159]; //added 1 to prevent out of bounds memory access

for(k=0;k<158;k++){
data[k]=malloc(sizeof(person_count));
fscanret=fscanf(eduData,"%s %i %i\n",data[k]->country,&data[k]->females,&data[k]->males);
if (fscanret==EOF){ //check return value to avoid going past end of file
free(data[k]); //discard empty record and free memory if EOF reached
k--;
break;
}
printf("%s %i %i\n",data[k]->country,data[k]->females,data[k]->males);
}
fclose(eduData);

printTable(data,k); //print k number of entries.

while (k>=0){
free(data[k]); //free memory for all entries. DONT FORGET THIS
k--;
}

return 0;
}

关于当函数打印指针数组的内容时,c 程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36923808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com