This question already has answers here:
Closed 7 years ago.
Possible Duplicate:
How do I correctly set up, access, and free a multidimensional array in C?
I am trying to dynamically allocate memory for a 2D array using calloc. The columns are fixed as 2 so its only the rows that are dynamic.
Here is what I have been trying :
unsigned int **pts, rows;
int main()
{
//some code
pts = (unsigned int **)calloc(2*rows, sizeof (unsigned int **));
}
//The code to access the array :
for(k=1;k<=i;k++)
{
printf("\nX%d=",k);
scanf("%d",&pts[k][0]);
printf("\nY%d=",k);
scanf("%d",&pts[k][1]);
}
But the problem is, while accessing the array, the program crashes.
I am using Eclipse with MinGW GCC.
Please let me know if I need to put more data here or give me some idea how I can deal with this, as this is my first post.
Tudor's answer is the correct solution.
But to provide a bit more insight into why your code is wrong....
What your code is really doing is just to allocate an array, of length 2 * rows, of pointer to pointer to type int.
What you are trying to create is this:
an array of int** -> int* -> int
-> int
-> int
-> ...more
-> int* -> int
-> int
-> int
-> ...more
-> int* -> int
-> int
-> int
-> ...more
-> ...more
What you have actually created is this:
an array of int** -> int* -> nothing (null address)
-> int* -> nothing...
-> ...more
You then attempt to assign an int to one of the null address pointed by one of the zero-initialized int* in your array of int** (You see, calloc has made sure that all your int*'s are zero)
When you are trying to execute
scanf("%d",&pts[k][0]);
pts[k] refers to the (k - 1)th element in your array of int**, but as shown above, though your code has allocated space for this element indeed, it has initialized it as zero. So, this pts[k] points at NULL. So scanf has obtained an address based on a zero offset from the NULL address... It should be now clear to you that this is invalid.
Here's the way to do it:
pts = (unsigned int **)calloc(rows, sizeof (unsigned int *));
for(int i = 0; i < rows; i++) {
pts[i] = (unsigned int *)calloc(2, sizeof (unsigned int));
}