2-D Array and Pointers

Jun 13, 2012 at 8:22pm
We have a 2-D array a[][].
we want to return it from a function.
we have three ways of returning.
1. int *a;
int *fun1(); //fun prototype

int *fun1() //fun definition
{
static int a[ROW][COL]= {
1,2,3,4,
5,6,7,8,
9,0,1,6
};
return (int *)a;
}

what is (int *)a?
what if we write return a;

2. int (*a)[COL];
int (*fun2())[COL]; //function prototype

int (*fun2())[COL] //function definition
{
.......
.........
return a;
}

Does a hold the address of 0th element of 1st array???How???
what if we write return (int*)a;


3. int (*a)[ROW][COL];
int (*fun3())[ROW][COL]; //function prototype

int (*fun3())[ROW][COL] //function definition
{
.....
....

return (int(*)[ROW][COL])c;
}

what is (*fun3())[ROW][COL] shows???
what does (int(*)[ROW][COL])c indicates and how ????

Someone Help me!!!!
Plzzzzzzzzzzzzzz......
Jun 13, 2012 at 8:42pm
When a name of an array is used in expressions it is converted to the pointer to its first element.

Element of a one-dimensional array is a scalar object.

So if you have for example

int a[] then using "a" in expressions becomes int *a

By analogy

int [] -> int *

int [][N] -> int ( * )[N]

int [][M][N] -> int ( * )[M][N]

and so on.

We have a 2-D array a[][].
we want to return it from a function.
we have three ways of returning.
1. int *a;
int *fun1(); //fun prototype

int *fun1() //fun definition
{
static int a[ROW][COL]= {
1,2,3,4,
5,6,7,8,
9,0,1,6
};
return (int *)a;
}

what is (int *)a?
what if we write return a;


We can return arrays only either as a reference to the array or as a pointer to its first element. As I have described above for two-dimensional arrays their name are converted to pointers to their first elements that is int a[ROW][COL] will be converted to int ( * )[COL]

The address of int ( * )[COL] coinsides with the address of the a[0][0]. So the last statement in the function

return (int *)a;

makes a casting from int ( * )[COL] to int *. Their values of addresses are equal.

If we would want to return the expression a we shall change return type of the function from int * to int ( * )[COL] That means that the function shall be declared as

int ( *fun1() )[COL] //fun definition
{
static int a[ROW][COL]= {
1,2,3,4,
5,6,7,8,
9,0,1,6
};
return a;
}

If you have understood what I said you can answer other your questions yourself.
Last edited on Jun 13, 2012 at 8:47pm
Topic archived. No new replies allowed.