2

This seems like a silly question. I have an array of chars and want to store the address of the array in another variable, but can't seem to declare the correct type for the array address (I'm using gcc):


IN:

int main(void){
  char cha[] = "abcde";
  char **arrayAddress = &cha;
}

OUT:

arrayaddress.c: In function ‘main’:
arrayaddress.c:3:25: warning: initialization of ‘char **’ from incompatible pointer type ‘char (*)[6]’ [-Wincompatible-pointer-types]
    3 |   char **arrayAddress = &cha;
      |                         ^

This is expected, I have read elsewhere that the type of cha should be char(*)[6]. But when I try to declare arrayAddress with this type, my program fails:


IN:

int main(void){
  char cha[] = "abcde";
  char (*)[6]arrayAddress = &cha;
}

OUT:

arrayaddress.c: In function ‘main’:
arrayaddress.c:3:10: error: expected identifier or ‘(’ before ‘)’ token
    3 |   char (*)[6]arrayAddress = &cha;
      |          ^
make: *** [<builtin>: arrayaddress] Error 1
       ^

How do I define arrayAddress correctly?

  • What do you want to do with that address? You can store the address as `char *arrayAddress = cha;` but that may or may not be what you need depending on how you want to use it. – kaylum Jan 18 '22 at 22:30
  • 2
    It is purely for educational purposes. I was reading about the differences between pointers and arrays in C and just started wondering why I couldn't declare it. I could always just dereference the array, but for example one usecase would be to see how adding 1 to `arrayAddress` gives a different address than adding 1 to `cha[0]` – DancingIceCream Jan 18 '22 at 22:38

3 Answers3

5

It is written:

char (*arrayAddress)[6] = &cha;

Notice that the name of variable gets tucked in middle of the expression.

kirjosieppo
  • 617
  • 3
  • 16
0

Arrays decay to pointers.

  char cha[] = "abcde";

  char *p1 = cha;

  char (*arrayptr)[sizeof(cha)] = &cha;

cha, &cha[0] and &cha reference the same first element of the array cha, the only difference is the type.

  1. cha and &cha[0] has type: pointer to char
  2. &cha has type: pointer to array of 6 char elements.
Chris
  • 26,361
  • 5
  • 21
  • 42
0___________
  • 60,014
  • 4
  • 34
  • 74
  • 1
    As arrays do not always _deday to pointers_ (decay), "`cha`, ... reference the same first element of the array `cha`" oversimplifies. `cha` has type of "array 6 of char" and sometimes its converts to a pointer. Example where it does not convert: `[sizeof(cha)]` is not the size of a pointer, but the size of an array. – chux - Reinstate Monica Jan 18 '22 at 23:00
0

If your compiler supports typeof extension (gcc does) then you can define the pointer as:

typeof(char (*)[6]) arrayAddress = &cha;

Or even cleaner as:

typeof(char[6]) * arrayAddress = &cha;
tstanisl
  • 13,520
  • 2
  • 25
  • 40