【发布时间】:2017-05-13 16:24:32
【问题描述】:
函数获取一个成绩数组,如果元素少于之前,则更改成绩的数量函数将删除这些元素 例如:之前:我在另一个函数中输入了3个等级:100、90、80。 之后:在这个功能中它要求我输入新的金额,我输入,然后输入它的等级,70。 在我将它返回到 main 并将数组 Grades 发送到一个打印数组的函数之后,它保留了 3 个元素,100、90、80。 请帮助我,我尝试了很多时间,但没有成功。
void changeNumOfGrades(int* grades, int size)
{
int numOfGrades = 0;
int i = 0;
do
{
if (i > ONE_ITERATION)
{
printf("Please enter positive number...\n");
}
printf("How many elements would you like? ");
scanf("%d", &numOfGrades);
i += 1;
} while (numOfGrades < 0);
grades = realloc(grades, numOfGrades*sizeof(int));
if (!grades)
{
printf("Unsuccessful realloc");
//There is no need to release memory because the realloc is for the same pointer.
}
if (numOfGrades > size)
{
printf("You have more grades than before,\nPlease enter their grades: \n");
int newGrade = 0;
//int newNumOfGrades = numOfGrades - size;
int i = 0;
for (i = size + 1; i <= numOfGrades; i++)
{
printf("Enter grade number %d: ", i);
scanf("%d", &newGrade);
*(grades + i - 1) = newGrade;
printf("hey %d", *(grades + 1));
}
}
}
【问题讨论】:
-
C11 标准草案 n1570:4 参数可以是任何完整对象类型的表达式。在准备调用函数时,会评估参数,并为每个参数分配相应参数的值。 93) 函数可以改变其参数的值,但这些改变不会影响参数的值。[...]
-
此函数签名:'void changeNumOfGrades(int* Grades, int size)' 不能更改 '*grades' 参数的值,因为它是按值传递的。
-
你调用
realloc()的grades指针之前的值是多少? 之后的值是多少?在您调用changeNumOfGrades()之前,指针inmain()的值是多少?main()在你调用changeNumOfGrades()之后指针的值是多少?