0

I have created a 2D-array in following way:

int** map_array = (int**)malloc(sizeof(yy_value*xx_value));

When i try to assign a value on a position:

map_array[y*xx_value+x] = 5;

I get following error:

Assigning to 'int *' from incompatible type 'int'

What am i doing wrong here?

2 Answers 2

4

Change:

int** map_array = (int**)malloc(sizeof(yy_value*xx_value));

to:

int* map_array = (int*)malloc(yy_value*xx_value*sizeof(map_array[0]));

Explanation: you're allocating a "flattened" 2D array here, where you calculate your own 1D index rather than an actual 2D array. Also the size passed to malloc was incorrect.

Note that you should probably not be using malloc in a C++ program without a good reason.

Sign up to request clarification or add additional context in comments.

Comments

1

you can alternatively use a 2D array as:

int **map_array = (int**)malloc(xx_value*sizeof(int*))
for (i = 0; i < xx_value; i++) {
    map_array[i] = (int*)malloc(yy_value*sizeof(int))
}

and access elements using:

map_array[x][y] = 5;

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.