c语言程序设计(关于动态内存分配)问题。高手进
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
void main()
{
int n,i,k,m,sum=0,*p,hign_score,low_score; //定义常量
float ave_score;
printf("please input the number of the students:");
scanf("%d",&n);
p=(int*)malloc(n*sizeof(int)); //动态内存分配
if(p==NULL)
{
printf("Insufficient memory avaiable.");
exit(0);
}
printf("please input the scores of the students:");
for(i=0;i<n;i++)
scanf("%d",p+i); //输入学生的分数
for(k=0;k<n;k++) //找最低的成绩
{
if(*p>*(p+k))
{
m=*p;
*p=*(p+k);
*(p+k)=m;
}
}
for(k=0;k<n;k++) //找最高的成绩
{
if(*(p+n)<*(p+k))
{
m=*(p+n);
*(p+n)=*(p+k);
*(p+k)=m;
}
}
for(i=0;i<n;i++)
sum+=*(p+i);
ave_score=sum*1.0/n;
hign_score=*(p+n);
low_score=*p;
free(p);
printf("The average score of the students is %f",ave_score); //输出
printf("The high score of the students is %d",hign_score);
printf("The low score of the students is %d",low_score);
} 展开
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
void main()
{
int n,i,k,m,sum=0,*p,hign_score,low_score; //定义常量
float ave_score;
printf("please input the number of the students:");
scanf("%d",&n);
p=(int*)malloc(n*sizeof(int)); //动态内存分配
if(p==NULL)
{
printf("Insufficient memory avaiable.");
exit(0);
}
printf("please input the scores of the students:\n");
for(i=0;i<n;i++)
scanf("%d",p+i); //输入学生的分数
for(k=0;k<n;k++) //找最低的成绩
{
if(*p>*(p+k))
{
m=*p;
*p=*(p+k);
*(p+k)=m;
}
}
for(k=0;k<n;k++) //找最高的成绩,
{
if(*(p+n-1)<*(p+k)) //这个地方你出错了,有n个学生,它的地址应该是
{ //p+n-1,你用的是p+n,指向任何数,出错。
m=*(p+n-1);
*(p+n-1)=*(p+k); //同理,都是p+n-1
*(p+k)=m;
}
}
for(i=0;i<n;i++)
sum+=*(p+i);
ave_score=sum*1.0/n;
hign_score=*(p+n-1); //也应该是p+n-1
low_score=*p;
printf("The average score of the students is %f\n",ave_score); //输出
printf("The high score of the students is %d\n",hign_score);
printf("The low score of the students is %d\n",low_score);
free(p);
}
PS:指针的题目容易出错,用的什么要小心。如果没有语法错误,出错的话,一般就是指针的地址有问题。
程序是对的,有运行结果。结贴吧
你的n都没初始化怎么能使用来作为地址的索引呢
也能显示结果 就是最高分不对
没有error,但无法运行