Nimrod Shai
Nimrod Shai

Reputation: 1179

reallocating size of array gives me no change

I'm trying to realloc the size of my array but it doesn't change. I can separate it to two issues:

Coordinate *closeCoordinatesArray = malloc(sizeof(Coordinate) * 0);

    Coordinate nextCoordinate = coordinatesMainArray[nextCoordinateIndex];

    for (int p = 0; p < 4; p++) {
        switch (p) {
            case 0:
                if (((nextCoordinate.x - 1) >= 0) && ((nextCoordinate.y - 1) >= 0)) {
                    int sizeOfArray = sizeof(*closeCoordinatesArray);
                    int sizeOfFirstObject = sizeof(closeCoordinatesArray[0]);
                    int closeCoordinatesArrayLength = (sizeOfArray / sizeOfFirstObject);

                    closeCoordinatesArray = realloc(closeCoordinatesArray,sizeof(Coordinate) * (closeCoordinatesArrayLength + 1));

                    sizeOfArray = sizeof(*closeCoordinatesArray);
                    sizeOfFirstObject = sizeof(closeCoordinatesArray[0]);
                    closeCoordinatesArrayLength = (sizeOfArray / sizeOfFirstObject);

After i malloc it in the first row, it shows that its length is 1. I would assume it should be 0 (i want it to be 0).

After a realloc it in case 0 I check the length and it's still 1.

What am i doing wrong?

Upvotes: 0

Views: 76

Answers (1)

Bathsheba
Bathsheba

Reputation: 234645

It's important to remember that sizeof is evaluated at compile time; therefore it could not know about a variable length array. All it gives you is the size of the implicit pointer associated with the array. (Remember that in C pointers and arrays are equivalent).

Upvotes: 7

Related Questions