I’m trying to grasp the differences between these three declarations:
char p[5];
char *p[5];
char (*p)[5];
I’m trying to find this out by doing some tests, because every guide of reading declarations and stuff like that has not helped me so far. I wrote this little program and it’s not working (I’ve tried other kinds of use of the third declaration and I’ve ran out of options):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void) {
char p1[5];
char *p2[5];
char (*p3)[5];
strcpy(p1, "dead");
p2[0] = (char *) malloc(5 * sizeof(char));
strcpy(p2[0], "beef");
p3[0] = (char *) malloc(5 * sizeof(char));
strcpy(p3[0], "char");
printf("p1 = %s\np2[0] = %s\np3[0] = %s\n", p1, p2[0], p3[0]);
return 0;
}
The first and second works alright, and I’ve understood what they do. What is the meaning of the third declaration and the correct way to use it?
Thank you!
The third is a pointer to an array of 5 chars, whereas the second is an array of 5 pointers to char.
Imagine it like this:
Whereas the second one looks like that:
This is one of the cases where understanding the difference between pointers and arrays is crucial. An array is an object whose size is the size of each of its elements times the count, whereas a pointer is merely an address.
In the second case,
sizeof(p)will yield5 * the_size_of_a_pointer.In the third case,
sizeof(p)will yieldthe_size_of_a_pointer, which is usually4or8, depending on the target machine.