2D array, compiler error

I

Imran

Hello all, I am trying to pass 2D array to a func, as follows, it is showing
compiler error.

void helloptr(int **a){

a[0][0] = 0xB;

}

int main(int argc, char* argv[]){

int a[10][10]={0};

helloptr(a);

return 0;

}
 
B

Ben Pfaff

Imran said:
Hello all, I am trying to pass 2D array to a func, as follows, it is showing
compiler error.

void helloptr(int **a){

a[0][0] = 0xB;

}

int main(int argc, char* argv[]){

int a[10][10]={0};

helloptr(a);

return 0;

}

This is in the FAQ.

6.18: My compiler complained when I passed a two-dimensional array to
a function expecting a pointer to a pointer.

A: The rule (see question 6.3) by which arrays decay into pointers
is not applied recursively. An array of arrays (i.e. a two-
dimensional array in C) decays into a pointer to an array, not a
pointer to a pointer. Pointers to arrays can be confusing, and
must be treated carefully; see also question 6.13.

If you are passing a two-dimensional array to a function:

int array[NROWS][NCOLUMNS];
f(array);

the function's declaration must match:

void f(int a[][NCOLUMNS])
{ ... }

or

void f(int (*ap)[NCOLUMNS]) /* ap is a pointer to an array */
{ ... }

In the first declaration, the compiler performs the usual
implicit parameter rewriting of "array of array" to "pointer to
array" (see questions 6.3 and 6.4); in the second form the
pointer declaration is explicit. Since the called function does
not allocate space for the array, it does not need to know the
overall size, so the number of rows, NROWS, can be omitted. The
width of the array is still important, so the column dimension
NCOLUMNS (and, for three- or more dimensional arrays, the
intervening ones) must be retained.

If a function is already declared as accepting a pointer to a
pointer, it is almost certainly meaningless to pass a two-
dimensional array directly to it.

See also questions 6.12 and 6.15.

References: K&R1 Sec. 5.10 p. 110; K&R2 Sec. 5.9 p. 113; H&S
Sec. 5.4.3 p. 126.
 
C

CBFalconer

Imran said:
Hello all, I am trying to pass 2D array to a func, as follows, it
is showing compiler error.

void helloptr(int **a) {

a[0][0] = 0xB;
}

What 2d array? All I see is a pointer to a pointer to int.
Sometimes this may be used to reference a 1d array of pointers to
ints. Read the faq.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top