0

I have problem working with dynamic array of pointer structs. It seemed that at the end of the loop array have only 2 pointers inside. I don't know why is that. I new to C and low level stuff. I am asking for help! Could You please explain me why this is happening? enter image description here

#include <stdlib.h>

struct Coordinates {
    short x;
    short y;
};

const short BOARD_SIZE = 8;
const short MAX_SIZE = 10;

int main() {


    struct Coordinates **possible_moves = malloc(MAX_SIZE * sizeof(struct Coordinates));

    for (short i = 0; i < BOARD_SIZE; ++i) {
        struct Coordinates *current_coordinates = malloc(sizeof(struct Coordinates));
        current_coordinates->x = i;
        current_coordinates->y = i;
        possible_moves[i] = current_coordinates;
    }

    return 0;
}
1
  • 1
    There is a typo in this declaration struct Coordinates **possible_moves = malloc(MAX_SIZE * sizeof(struct Coordinates));. You mean sizeof(struct Coordinates *) Commented Oct 22, 2020 at 20:06

2 Answers 2

1

The elements of the array to be assigned to possible_moves is pointers, so allocating size should be one of pointers, not one of the structure.

In other words,

    struct Coordinates **possible_moves = malloc(MAX_SIZE * sizeof(struct Coordinates));

should be

    struct Coordinates **possible_moves = malloc(MAX_SIZE * sizeof(struct Coordinates*));

or

    struct Coordinates **possible_moves = malloc(MAX_SIZE * sizeof(*possible_moves));
Sign up to request clarification or add additional context in comments.

Comments

1

Or you can do like this :

#include <stdlib.h>

struct Coordinates {
    short x;
    short y;
};

const short BOARD_SIZE = 8;
const short MAX_SIZE = 10;

int main() {
    // struct Coordinates * instead of struct Coordinates **
    struct Coordinates *possible_moves = (Coordinates *)malloc(MAX_SIZE * sizeof(struct Coordinates));

    for (short i = 0; i < BOARD_SIZE; ++i) {
        // struct Coordinates instead of struct Coordinates *
        struct Coordinates current_coordinates = {i, i};
        possible_moves[i] = current_coordinates;
    }
    free(possible_moves);
    return 0;
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.