Is anything wrong with the following piece of code?
int x[3][12];
int *ptr[12];
ptr=x;
Is anything wrong with the following piece of code?
int x[3][12];
int *ptr[12];
ptr=x;
Yes, it fails to compile with the message:
'=' : cannot convert from 'int [3][12]' to 'int *[12]'
Explanation:
Here x
is a 2 dimensional array of ints, while ptr
is an array of pointers to int.
The statement ptr=x
is trying to assign x
(which is a 2 dimensional array of ints) to ptr (which is an array of pointers to int).
If you were to declare ptr as
int (*ptr)[12];
instead, then ptr would be a pointer to an array of ints, and since a pointer to an array of ints is essentially the same thing as a 2 dimensional array of ints (an array of ints is just a pointer to the first element in the array, and a 2 dimensional array of ints is just a pointer to the first array of ints) then it would compile.
Alternatively consider this:
int x[3][12];
int *ptr[12];
ptr[0] = x[0];
which is a valid assignment of an array of ints to a pointer to int (note that the fact that the second dimension of x is the same as ptr is not why this works)
Have a look at: C pointer to array/array of pointers disambiguation
I got a bit intrigued by this and did a working example:
#include <stdio.h>
int main (int argc, char * argv[])
{
int i,j;
int x[3][12]; // An array of arrays with lenght 12
//int *wrong[12]; // An array of pointers to ints.
int (*ptr)[12]; // A pointer to an array of ints
/* Initialization to consequtive numbers*/
for ( i = 0; i < 12*3; i++)
{
/* Get the first index, and go from there */
int *number = &(x[0][0])+i;
*number = i;
}
/* Iterate throug and check that the pointers are the same */
for ( i = 0; i < 3 ; i ++ )
{
/* This will generate a warning:
* assignment from incompatible pointer type [enabled by default]
*/
ptr = x[i];
fprintf(stderr,"Numbers in ptr: ");
for ( j = 0; j < 12; j ++)
fprintf(stderr,"%2d ", (*ptr)[j]);
fprintf(stderr,"\n");
fprintf(stderr,"Numbers in x: ");
for ( j = 0; j < 12; j ++)
fprintf(stderr,"%2d ", x[i][j]);
fprintf(stderr,"\n");
}
return 0;
}
The output is:
Numbers in ptr: 0 1 2 3 4 5 6 7 8 9 10 11
Numbers in x: 0 1 2 3 4 5 6 7 8 9 10 11
Numbers in ptr: 12 13 14 15 16 17 18 19 20 21 22 23
Numbers in x: 12 13 14 15 16 17 18 19 20 21 22 23
Numbers in ptr: 24 25 26 27 28 29 30 31 32 33 34 35
Numbers in x: 24 25 26 27 28 29 30 31 32 33 34 35