I need a simple example of passing a 2D array to a function from C
I would like to create a C function that takes a 2D array of doubles as a parameter and operates on that array through indexing, for example. printf("%f ", array[i][j])
...
What I have been able to gather from various examples and SO questions looks something like this:
void printArray(double **array, int m, int n)
{
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%f ", array[i][j]);
}
printf("\n");
}
}
Q. main
I can successfully print an array like this:
int i, j, k = 0, m = 5, n = 6;
double **a = malloc(m * sizeof(*a));
//Initialize the arrays
for (i = 0; i < m; i++)
{
a[i] = malloc(n * sizeof(*(a[i])));
}
for (i = 0; i < m; i++)
{
for (j = 0; j<n; j++)
{
k++;
a[i][j] = k;
}
}
printArray(a, m, n);
However, when I try to initialize the array to some given values ββand then call:
double a[5][6] = { { 1, 2, 3, 4, 5 ,6},
{ 1, 2, 3, 4, 5, 6},
{ 1, 2, 3, 4, 5, 6},
{ 1, 2, 3, 4, 5, 6},
{ 1, 2, 3, 4, 5, 6} };
printArray(a, 5, 6);
I am encountering the following error:
Unhandled exception at 0x011514D3 in Example.exe: 0xC0000005:
Access violation reading location 0xA1F8E3AC.
Can someone please explain what my error is and how to fix it? rev
Note that for defining the function, I will know the size of the array at runtime, but not at compile time. Also, I am going to Windows with VisualStudio 2013.
source to share
double a[5][6]
is of a type double[][6]
that is not the same as double**
. double**
is a pointer to a pointer to double. double[][6]
is a compiler-controlled data type that is a two-dimensional array.
What happens here is what is created double[][6]
when clicked is printArray
attached to double**
.
If your function will accept double**
, you need to pass it double**
. You can initialize the contents of an array by filling each array of elements separately:
double row1 [3] = {3, 4, 5}; a [1] = row1;
It works around the problem; because it double[]
is stored by the compiler as a contiguous array of values double
, implicitly casting it to double*
as above.
Another solution is to change the function to take the "real" instead of the "pointer-pointer" double[][6]
. How you do this with non-fixed sized arrays depends on your particular C brand; As far as I know, this is not part of the C standard.
The third solution is to build the array line by line with malloc
and fill it with cell by cell a[0][0] = 1
and so on. You already have this in your question and it is working correctly.
The last thing to know is what you allocate onto the a
stack: when the function main
finishes, accessing it will result in undefined behavior.
source to share