Reputation: 1135
I was trying to initialize and print array of pointers to integers. Is this method of initialization is correct or any other method is available to initialize when we declare it as array of pointers. We can also use traditional array of arrays ar1[][] anyway.
#include <stdio.h>
#include <stdlib.h>
#define NUM_COLS 4
#define NUM_ROWS 3
int main(void)
{
int rowCnt;
int colCnt;
int *ar2[NUM_ROWS]={
(int[]){11,12,13,14},
(int[]){21,22,23,24},
(int[]){31,32,33,34},
};
for(rowCnt=0;rowCnt<NUM_ROWS;rowCnt++)
{
for(colCnt=0;colCnt<NUM_COLS;colCnt++)
{
printf("%d\t",*(*(ar2+rowCnt)+colCnt));
}
printf("\n");
}
return(0);
}
Upvotes: 0
Views: 102
Reputation: 141628
This initialization is correct; compound literals have lifetime to match the block they are declared in. The literals have the same lifetime as ar2
in this case.
However I would recommend using a simple array as in dbush's answer unless you have some extra requirement (such as wanting rows of differing lengths).
Upvotes: 1
Reputation: 594
This declaration below is incorrect.
int *ar2[NUM_COLS]={
(int[]){11,12,13,14},
(int[]){21,22,23,24},
(int[]){31,32,33,34},
};
This is an array of NUM_COLS of pointers to ints. The memory of these pointers to ints do not get properly allocated this way, and will result in undefined behavior.
If you wanted to allocate the entire array on the stack, you could do something like this:
int ar2[NUM_ROWS][NUM_COLS]= {
{11,12,13,14},
{21,22,23,24},
{31,32,33,34},
{0,0,0,0}
};
If you want the pointers to ints to be properly on the heap, you should use malloc/free respectively
int *ar2[NUM_ROWS];
for (int i = 0; i < NUM_ROWS; ++i)
{
ar2[i] = (int*)malloc(sizeof(int) * NUM_COLS);
}
///now you can set up your arrays
memcpy(ar2[0], (int []){11,12,13,14}, 4 * sizeof(int));
memcpy(ar2[1], (int []){21,22,23,24}, 4 * sizeof(int));
memcpy(ar2[2], (int []){31,32,33,34}, 4 * sizeof(int));
///Do what you want with the array
...
///Free array once you are done
for (int i = 0; i < NUM_ROWS; ++i)
{
free(ar2[i]);
}
Upvotes: 1
Reputation: 224377
Since you know the number of rows and colums, you can define a 2D array (formally an array of arrays) instead of an array of pointers:
int ar2[NUM_ROWS][NUM_COLS]={
{11,12,13,14},
{21,22,23,24},
{31,32,33,34},
};
Upvotes: 1