简体   繁体   中英

passing a 2D array to a function

gcc 4.6.2 c89

I have the following 2D array that I want to pass to a function:

char elements[MAX_NUM_ELEMENTS][MAX_STRING_LEN] = {{0}};

My function prototype is:

int get_elements(char **elements)

And I am calling the function like this:

get_elements(elements);

However, I get the following error:

expected ‘char **’ but argument is of type ‘char (*)[128]’

All arrays declay into pointers, so sure why I can't just pass the pointer.

Many thanks for any advice,

"All arrays decay into pointers" is a common misconception about C.

The first few answers in this FAQ clarify the issue.

You can cast:

get_elements((char **) elements);

char ** and char[128][128] are obviously different types.

Your prototype looks very broken, it lacks a type name.

And you can't use a "decayed" pointer, since that would lose the information about the dimensions of the array, which are (obviously) needed in order to compute accesses properly.

The best way, in my opinion, is to pass a pointer to the first element, along with the dimensions as needed. For 2D, this would do:

int get_elements(int *elements, size_t width, size_t height);

This also requires that you decide, and adhere to, an in-memory layout for your elements, such as column-major or row-major. This affects how you compute the address for a given element.

"Two -dimensional Array and Double Pointer are not the Same" "A two - dimensional Array is a array of pointers"

Is what I learnt/memorized while reading about array and pointer

Say elements- data has memory startin Location 100 .. And the elements Pointer has memory at Location 50 ..

The element data gets allocated memory from 100 to 100+MAX_NUM_ELEMENTS * MAX_STRING_LEN -1.. And you need to access data from 100 ..

But you are passing element as a double pointer .. so it tries to access ( 50->100->Actual data's) Location instead of accessing ( 50-> 100)'s location ..

If you change the prototype to int get_elements( char *element[]) .. It will work ..

If the object to pass to your function is defined as:

char elements[MAX_NUM_ELEMENTS][MAX_STRING_LEN];

Your function prototype should not be:

int get_elements(char **elements)

but rather:

int get_elements(char elements[][MAX_STRING_LEN])

or

int get_elements(char (*elements)[MAX_STRING_LEN])

(both forms are equivalent)

The reason for this is the type of the value of an object of type

char [MAX_NUM_ELEMENTS][MAX_STRING_LEN]

is

char (*)[MAX_STRING_LEN] (a pointer to an array of MAX_STRING_LEN chars) and not char ** (a pointer to a pointer of char ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM