gpt4 book ai didi

c - 在 C 中使用指针的程序崩溃。找不到错误

转载 作者:行者123 更新时间:2023-11-30 21:17:33 25 4
gpt4 key购买 nike

我编写了一个接受学生人数和科目数量的程序。我需要接受每个学生所有科目的分数并打印每个学生的总分。我使用指针而不是数组,因为我们不知道学生/科目的数量。导致问题的函数可能是这个:n=students,m=subjects,sm 是一个包含指针“marks”的结构体的指针对象。

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

void accept(int,int); //Function Prototype
void calc(int,int);//Function Prototype
void print(int);//Function Prototype
struct student{
float *marks;
}*sm;
float *total;
int main(){
int n,m;
printf("Enter number of students(N) and number of subjects(M) \n");
scanf("%d%d",&n,&m);
sm=malloc(n);
sm->marks=malloc(m);
total=malloc(n);
accept(n,m);
calc(n,m);
print(n);
return 0;
}
void accept(int n,int m){ //Accepts data
int i,p;
for(i=0;i<n;i++){
printf("Enter the marks of student %d in each subject in order and separated by a space/line \n",i+1);
for(p=0;p<m;p++){
scanf("%f",(sm+i)->marks+p);
}
}
}
void calc(int n,int m){ //Calculates total marks
int i,p,tot=0;
for(i=0;i<n;i++){
for(p=0;p<m;p++){
tot+=*((sm+i)->marks+p);
}
*(total+i)=tot;
tot=0;
}
}
void print(int n){//Print the total marks of each student
int i,tot=0;
for(i=0;i<n;i++){
printf("Total marks for student %d is:%0.2f \n",i+1,*(total+i));
}
}

只要学生数量>1,程序就会崩溃。我不明白为什么,我尝试了很多方法来解决它,但到目前为止没有一个有效。我的错误是什么?

最佳答案

在您的 main 函数中,您有以下行:

sm=malloc(n);

分配n 字节。不是 n 个结构元素。因此,您很可能会远远超出您分配的内存范围并出现未定义的行为

你需要做

sm = malloc(n * sizeof *sm);  // Allocates n structures

然后,如果将 sm 视为指向单个结构的指针(当它应该是数组时),则情况会变得更糟。

关于c - 在 C 中使用指针的程序崩溃。找不到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39163003/

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