2

Is Str a "pointer" or a "pointer to pointer" in Str[3][5]?

I usually declare char **Str to make a simulated 2D array, but how to send the address of Str[3][5] to another function, and how to set the parameter of that function in order to modify values in Str[3][5] ?

As far as I know, the compiler treats a 2D array as an ordinary array, so I should send Str (a pointer) to the other function. But how to modify the value of Str[3][5] via the received pointer?

Kevin Dong
  • 5,001
  • 9
  • 29
  • 62

2 Answers2

5

An array of T when used in most expressions will decay to a pointer of type "pointer to T" and have the value equal to the address of the first element of the array.

If Str is declared as:

char Str[3][5];

Then Str will decay to char (*)[5], and have the value of &Str[0]. If passing to a function, you can declare the function as follows:

void foo (char (*str)[5], size_t n);

And within foo(), you would access str as you would access Str itself.

undur_gongor
  • 15,657
  • 5
  • 63
  • 75
jxh
  • 69,070
  • 8
  • 110
  • 193
0

Pointer address in a C multidimensional array

To expand on this answer to a similar question, when we type to get addresses of arrays. The name of the array is actually a pointer to the first variable in the array.

You can't really pass a pointer of a particular part of an array, as what we interact with in coding is the pointer itself. (array + 1) == array[1] Let's say we have create an array pointer int* arrayPointer; and you want to get the second variable in the array. You could either assign arrayPointer = array + 1 or arrayPointer = &array[1]

So if you want to modify part of array[3][5] the easiest way is to pick that part of the array and assign a variable to it. For example if you want to modify the first "column" and first "row" you would type...

array[0][0] = variable

Hope this helps.

Community
  • 1
  • 1
Scott
  • 1,154
  • 1
  • 12
  • 25
  • 1
    `array` is `&array[0]` actually. (when not used as operand of unary `&` or `sizeof`) – M.M Jun 25 '14 at 03:33