Reputation: 1045
How do I define a 2D array where the first dimension is already defined with MAX_VALUES. I wish to be able to allocate memory to the second dimension. Below is what I have attempted. I want an array with A[1000][mallocd]
#define MAX_VALUES 1000
int
main(){
int n= 10;
int *A[MAX_VALUES] = malloc(10 * sizeof(int));
}
Upvotes: 2
Views: 77
Reputation: 18321
int *A[MAX_VALUES]
is an array of int
pointers, which is already statically allocated. If you want to allocate some space pointed by each one of the pointers you will have to iterate on the array and assign each pointer with a different malloc
. Otherwise you will have to redefine your A
(as @haccks answer is suggesting, for example).
Upvotes: 1
Reputation: 2757
try this :
int*A[MAX_VALUES],n;
for(i=0;i<MAX_VALUES;i++)
A[i]=malloc(n*sizeof(int);
It will have MAX_VALUE rows with number of coloumns mallocked.
Upvotes: 1
Reputation: 106012
Try this
int (*A)[n] = malloc(MAX_VALUES * sizeof(*A));
It will allocate contiguous 2D array.
Upvotes: 2