0

I want to reallocate an array of structs in C (add one struct at the end) but it doesn't change its size:

typedef struct stone {
    int height;
    int width;
    int length;
    int color;
} STONE;

int main() {
    STONE *stone;
    stone = (STONE *)calloc(1, sizeof(STONE));
    int length = 0;
    int command = 1;
    while (command != 0) {
        printf("Choose the method: \n");
        printf("[0] - add stone\n");
        printf("[1] - show stone\n");
        printf("[2] - remove stone\n");
        printf("[3] - compare stone\n");
        printf("[4] - exit program\n");
        printf("Input: ");
        scanf("%d", &command);
        switch (command) {
        case 0:
            length++;
            stone= (STONE *)realloc(stone, sizeof(STONE) * length);
            STONE *d = stone+ (sizeof(STONE) * (length - 1));
            break;
        case 1:
            ausgabeBS(*(stone + length * sizeof(STONE) - sizeof(STONE)));
            break;
        case 2:
            break;
        case 3:
            break;
        default:
            return 0;
        }
    }
    return 0;
}

Why is this? I output the size of the array and it always stays at 4 Bytes.

//code I used to output the size
printf("%d", sizeof(stone));

I hope you can help me - thanks!

chqrlie
  • 131,814
  • 10
  • 121
  • 189
TheProgrammer
  • 784
  • 1
  • 6
  • 20
  • 2
    `stone` is a pointer, not an array. – Barmar Mar 07 '18 at 18:32
  • 1
    `sizeof(stone)` evaluates to the size *of the pointer*, not the thing it's pointing to. Also, post your code *here* - don't make us follow links. – John Bode Mar 07 '18 at 18:36
  • And please, check the return of the functions! what happen if calloc return a NULL? or realloc()? and still not into the code but for sure you will have, giving a position into the array, access to the information, in such scenario, please check boundaries! happy coding ;) –  Mar 07 '18 at 18:46

2 Answers2

0

First of all in C, Arrays and pointers are different.An array cannot be treated as a pointer to something.For understanding purpose you can assume array name suppose arr as const pointers (but they really are not a const pointer).So when realloc changes the address of arr variable, it cannot be changed.

Go through this discussion:Is an array name a pointer?

krpra
  • 466
  • 1
  • 4
  • 19
0

You cannot determine the size of the reallocated array from the pointer returned by realloc, you must keep track of the size manually, with a separate variable such as length.

sizeof(stone) evaluates to the size of a pointer, 4 bytes on your architecture.

Also note that indexing arrays is much simpler than what you write. You can calculate a pointer to the last element of the array this way:

STONE *d = stone + length - 1;

You can pass the last pointer in the array this way:

ausgabeBS(stone[length - 1]);
chqrlie
  • 131,814
  • 10
  • 121
  • 189