realloc函数不会在c中使用新值保存新元素

时间:2017-05-13 16:24:33

标签: c arrays realloc

如果元素少于函数删除这些元素之前的元素,

函数会获得一个等级数组并更改成绩数量 例如:之前:我输入了3个等级的另一个功能:100,90,80。 之后:在这个功能中它要求我输入新的金额,然后我输入,然后输入它的等级,70。 在我将它返回到主要并将数组,等级发送到打印数组的功能之后,它将保留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));
        }
    }

}

1 个答案:

答案 0 :(得分:0)

为了重新分配成绩,您需要传递**grades。 出于测试原因,我已更改size以获取新的分配大小,因此您可以在changeNumOfGrades之后打印数组

void changeNumOfGrades(int** grades, int *size/*get new 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 ++;
    } while (numOfGrades < 0);
    printf("%d",numOfGrades);
    *grades =  realloc(*grades, numOfGrades*sizeof(int));/*realloc **grade */
    if (!grades)
    {
        printf("Unsuccessful realloc");
        //There is no need to release memory because the realloc is for the same pointer.
    }
    printf("...\n");
    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));
        }
    }
    *size = numOfGrades;/*get new size allocated*/

}

void main()
{
    int numOfInts;
    int *grades ;
    grades =  malloc(3*sizeof(int));
    memset(grades,0,sizeof(int)*3);
    grades[0]=100;
    grades[1]=80;
    grades[2]=20;
    numOfInts = 3;/*initialize 3 items*/
    changeNumOfGrades(&grades,&numOfInts);
    printf("\n\n");
    for (int i=0;i<numOfInts;i++)
    {
        printf("%d\n",grades[i]);
    }
    free(grades);
}