gpt4 book ai didi

c - 分配内存后不执行代码

转载 作者:行者123 更新时间:2023-11-30 16:11:01 28 4
gpt4 key购买 nike

在我为结构数组分配一些内存后,Compile 甚至不执行单个“printf”函数,为什么会发生这种情况?

int main(){
setvbuf (stdout, NULL, _IONBF, 0);
int entry_size;
int all_ids [101] = {0};
int studentSize;
int max;
student* Students = readStudents ("students1.txt", &entry_size, all_ids, &studentSize);
printf ("%i \n", entry_size);
int i;
for (i = 1; i <= entry_size; i++){
if(all_ids[i] != 0) studentSize++;
}
topThreeAvg *averages = malloc(studentSize * (sizeof(topThreeAvg)));
for (i = 1; i <= entry_size; i++){
printf("%s %s %i %i\n", (Students + i) -> firstName, (Students + i) -> secondName, (Students + i) -> ID, (Students + i) -> grade);
}
max = getMaxGrade (Students, entry_size);
printf ("Max grade is %i \n", max);
fillAllStudentsAvgGrades (&averages, Students, entry_size, all_ids);
return 0;
}

最佳答案

topThreeAvg *averages = malloc(studentSize * (sizeof(topThreeAvg)));
for (i = 1; i <= entry_size; i++){
printf("%s %s %i %i\n", (Students + i) -> firstName, (Students + i) -> secondName, (Students + i) -> ID, (Students + i) -> grade);
}

您正在访问越界,请注意数组索引的范围是0...n-1,但您正在访问1...n

因此将循环更改为如下所示,

for (i = 0; i < studentSize ; i++){
<小时/>

旁注::另外

Students[i].ID

具有更好的可读性
(Students + i)->ID

关于c - 分配内存后不执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58745419/

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