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

标签 c

在我为结构数组分配一些内存后,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/

相关文章:

c - 在数组中找出重复的元素

c - 线程间通信,线程之间的切换

c - 函数参数无效

c - Linux 中 PTR_ALIGN 的用法

将 Intrinsic xmm 寄存器转换为 uint8_t 数组 [16]

c - 程序创建一个文件,但不会写入该文件

c - QNX VM 不支持 zmq_vmci?

c - 如何设置 "General->TargetName"、 "Debugging->Command"和 "Linker->General->Output File"

c - fgets() 的第一个实例被跳过

c - C 中 while 循环中的++i 和 i++