简体   繁体   中英

difference between char *(arr[5]) and char (*arr)[5]

It appears that I don't practically know the difference between char *(arr[5]) and char (*arr)[5] Logically, as it is with type-definitions, char *(arr[5]) is a pointer to an array of 5 char 's, char *arr[5] is an array of char pointers then what (*arr)[5] will be then? Or it makes no difference ?


I did some tests and found out that these 3 declarations are different. For instance if I use char (*arr)[5] it totally allows me to do that arr = malloc(2) , otherwise it moans about illegal conversions.


Can someone explain the differences between these declarations, when they are used and it will be a huge plus if this also includes may I do arr = malloc(2) to dynamically allocate an array of [5] chars, as it allows me to semantically do so with char (*arr)[5] although giving me stack overflows when being used. (disclaimer: [] suggests stack allocation, so it doesn't make much sense as a heap memory address cannot point to stack memory address as far as I am not aware)

char *(arr[5]) equals to char *arr[5] and it means you have array of pointers that each of them points to a character so arr[0] can points to a character and arr[1] can points to a character and so on. For example you can write your code like this:

char *(arr[5]);// or char *arr[5]
char a = 'a',b='b',c='c';
arr[0] = &a;
arr[1] = &b;
arr[2] = &c;    
printf("a=%c b=%c c=%c \n",*arr[0],*arr[1],*arr[2]);

But (*arr)[5] means you have an array of 5 characters and you want to point it.
For example you can write your code like this:

char (*arr)[5];
char str[5] = "Hell";
arr = &str;
printf("%s\n",*arr);

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