Abhishek wrote:
Yet another option is to use pointers to arrays:
int (*array4)[NCOLUMNS] = malloc(nrows * sizeof(*array4));
or even
int (*array5)[NROWS][NCOLUMNS] = malloc(sizeof(*array5));
Please explain the declaration of the multidimension array as shown
above.
how will u access the elements? Please explain with the help of a
diagram if possible.
Thank you for your patience.
This is a fair question and quite an uncommon syntax found in C.
C'mon you other guys, this is a forum to _help_ people with C
questions. Even if it is homework, let's provide some pointers (excuse
the pun).
OK, consider the following variable declarations:
int i;
int *pi; /* pointer to int */
int **ppi; /* pointer to pointer to int */
int ***pppi; /* pointer to pointer to pointer to int */
i = 1;
pi = &i;
ppi = π
pppi = &ppi;
Many people get confused by the levels of indirection you need to
access data in this kind of scenario.
Consider that:
printf("%d", i);
printf("%d", *pi);
printf("%d", **ppi);
printf("%d", ***pppi);
all will produce the same output. And so will:
printf("%d", pi[0]);
printf("%d", ppi[0][0]);
printf("%d", pppi[0][0][0]);
If you don't understand these concepts, then the answer to your
question will be very difficult to understand.
Now to follow your first example, consider an array:
int array3[NCOLUMNS];
Now I want a pointer to 'array3' called 'array4' please. It provides
one more level of indirection to the array.
int (*array4)[NCOLUMNS] = &array3;
To access the second element of the array you could use either:
array3[1]
or
(*array4)[1]
Now can you tell us how the 2D array (array5 in your example) would be
accessed the same way?
Feel free to ask more questions, but tell us how much you DO
understand. Which part is confusing you?
Lucien Kennedy-Lamb