Why can't we directly assign the address of a 2D array to a pointer?
Is there any way we can assign it in a single line, not with the help of a for loop?
Is there any other better approach?
// Array of 5 pointers to an array of 4 ints
int (*Aop[5])[4];
for(int i = 0;i<5;i++)
{
Aop[i] = &arr2[i]; //Works fine
}
//Why this doesn't work int
int (*Aop[5])[4] = &arr2[5][4]
This declaration
does not declare a pointer. It is a declaration of an array of 5 pointers to one-dimensional arrays of the the
int[4].Arrays do not have the assignment operator. However you could initialize it in its declaration as for example
or
Here is a demonstrative program.
The program output is
If you need to declare a pointer to the array
arr2then you should bear in mind that array designators are implicitly converted (with rare exceptions) to pointers to their first elements. The arrayarr2has elements of the typeint[4]. So a pointer to an object of this type will have the typeint ( * )[4]. So you can writeHere is another demonstrative program that uses pointers in for loops to output elements of the array
arr2.Again the program output is