2

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));

}
1
  • Your A has the wrong type, the * binds to the left. You want int (*A)[MAX_VALUES]. Commented Jun 5, 2015 at 17:14

3 Answers 3

2

Try this

int (*A)[n] = malloc(MAX_VALUES * sizeof(*A));  

It will allocate contiguous 2D array.

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

Comments

1

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.

1 Comment

This doesn't allocate a 2D array but several separate arrays. @haccks answer gives the correct approach.
1

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).

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.