0

whan I enter a bigger size to the array every thing just goes fine.

but if I put a smaller size it's just change the value in the array to some garbage value. Someone know's why?

int resize(int* calc, int size)
{
    int new_number = 0, i = 0;
    printf("Enter new number of grade: ");
    scanf("%d", &new_number);
    calc = (int*)realloc(calc, new_number * sizeof(int));
    if (new_number > size)
    {
        for (i = size + 1; i <= new_number; i ++)
        {
            printf("Enter grade %d: ", i);
            do
            {
                scanf("%d", &calc[i - 1]);
            } while (check_valid(calc, i));
        }
        size = new_number;
    }
    return size;
}
  • 1
    *but if I put a smaller size it's just change the value in the array to some garbage value* - what does it mean? The code posted does not deal with a smaller size. Post [mcve] with sample input and output. – Eugene Sh. Apr 20 '21 at 14:47
  • It is surprising that your code works for enlarging array. – MikeCAT Apr 20 '21 at 14:48
  • 1
    2 Issues here: 1) You should never assign result of `realloc` to same variable as you feed in as 1st parameter. In case of error `NULL` is returned and you lost the old address. 2) You cannot use the new pointer outside of your function as `calc` is just a copy of the passed value. To use it outside, you must add an exra `*`. – Gerhardh Apr 20 '21 at 14:50

1 Answers1

0

The value returned from realloc() may be different from what is passed.

The argument calc is a copy of what is passed, so modification of that will not affect what is passed.

To update the array correctly, you should receive a pointer to the pointer so that the pointer can be updated from the resize() function.

Also:

  • It looks weird to return old size when new size is smaller than new size while resizing is done in both case.
  • Casting results of malloc() family is considered as a bad practice.

Try this (make calc pointer to int* and add dereferences):

int resize(int** calc, int size)
{
    int new_number = 0, i = 0;
    printf("Enter new number of grade: ");
    scanf("%d", &new_number);
    *calc = realloc(*calc, new_number * sizeof(int));
    if (new_number > size)
    {
        for (i = size + 1; i <= new_number; i ++)
        {
            printf("Enter grade %d: ", i);
            do
            {
                scanf("%d", &(*calc)[i - 1]);
            } while (check_valid(*calc, i));
        }
    }
    return new_number;
}

and the calling will be like this:

int size = 0;
int* calc = NULL;
size = resize(&calc, size); /* add & to pass the pointer to the pointer */

instead of one for original function int resize(int* calc, int size):

int size = 0;
int* calc = NULL;
size = resize(calc, size);
MikeCAT
  • 73,922
  • 11
  • 45
  • 70