Reputation: 3
I have a static array that I want to use to initialize a dynamic array using pointers.
Right now I have this:
boardinit[BOARD_HEIGHT][BOARD_LENGTH] = {
{-4, -2, -3, -5, -6, -3, -2, -4},
{-1, -1, -1, -1, -1, -1, -1, -1},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{1, 1, 1, 1, 1, 1, 1, 1},
{4, 2, 3, 5, 6, 3, 2, 4},
};
int main()
{
int board[BOARD_HEIGHT][BOARD_LENGTH];
initboard(board);
for (int j = 0; j < BOARD_HEIGHT; j++)
{
for (int i = 0; i < BOARD_LENGTH; i++)
printf("%d ", board[j][i]);
printf("\n");
}
return 0;
}
void initboard(int (*pboard)[BOARD_HEIGHT])
{
for(int i = 0;i<BOARD_HEIGHT;i++)
pboard[i] = boardinit + i;
}
I want board[BOARD_HEIGHT][BOARD_LENGTH]
to initialize as boardinit[BOARD_HEIGHT][BOARD_LENGTH]
by passing board to initboard()
using pointers, but can't seem to get it to go.
Upvotes: 0
Views: 197
Reputation: 23236
"I have a static array that i want to use to initialize a dynamic array using pointers."
The problem with arrays of pointers is that each call to [m][c]alloc()
is not guaranteed (in fact is not likely) to provide a single contiguous block of memory. i.e., this is a common approach that provide many little areas of memory:
int **array = malloc(sizeof(width * sizeof(int *));
{
for(int i=0; i<width; i++)
{
array[i] = malloc(height*sizeof(int));
}
}
Thus, the initializer would need to be broken into several memory block locations.
A simpler and more efficient way to do this is with a single dynamic memory allocation call, guaranteeing a single contiguous block of memory, then a single memcpy()
is possible using the initializer into the pointer location returned from [m][c]alloc()
. The only problem then is how to access the memory area with array notation. The example below illustrates how this can be done using *(ptr + index)
notation...
//assuming your other code above
int main(void)
{
int elements = BOARD_HEIGHT*BOARD_LENGTH;
int *pArray = calloc(elements, sizeof(int));
if(pArray)
{
memcpy(pArray, boardinit, sizeof boardinit);
for(int i=0; i<BOARD_HEIGHT;i++)
for(int j = 0;j<BOARD_LENGTH;j++)
printf("%d\n", *(pArray + (i + j)));
free(pArray);
}
return 0;
}
Upvotes: 0
Reputation: 185
To copy the contents boardinit
to the value of board
, just use this:
memcpy(board, boardinit, sizeof(board));
If that does not work, try this:
void initboard(int pboard[BOARD_HEIGHT][BOARD_LENGTH]) {
for (int i = 0; i < BOARD_HEIGHT; i++)
for (int j = 0; j < BOARD_LENGTH; j++)
pboard[i][j] = boardinit[i][j];
}
Upvotes: 1