When I read books about C language, the two level pointer bothered me a lot.
char s[5][5];
char *s[5];
char (*s)[5];
so what is the difference between them?
What is the difference between char and char*? char[] is a character array whereas char* is a pointer reference. char[] is a specific section of memory in which we can do things like indexing, whereas char* is the pointer that points to the memory location.
Difference between char s[] and char *s in CThe s[] is an array, but *s is a pointer. For an example, if two declarations are like char s[20], and char *s respectively, then by using sizeof() we will get 20, and 4.
char a[]="string"; // a is an array of characters. char *p="string"; // p is a string literal having static allocation. Any attempt to modify contents of p leads to Undefined Behavior since string literals are stored in read-only section of memory.
It is short for character, which is a data type that holds one character (letter, number, etc.) of data. For example, the value of a char variable could be any one-character value, such as 'A', '4', or '#'.
In C, it is better to speak out the declaration. Then, it becomes intuitive. For this, you follow the right-left convention. Here is how it goes:
char *s[5];
How do you speak it? For that you start at the right of the variable name s
and then go to the left. So you start by saying "s is a/an", On the right, you see a []
and you say "s is an array ... ". And then you go to the left and see the *
, and say "s is an array of pointers." And that is what it is. It si an array of 5 pointers. You can store different pointers in this array.
Now for the other one:
char (*s)[5];
You start the same way. "s is a/an", and then look at the ()
. Anything within the ()
is bound to s
closer than anything outside. So the *
is more closely bound with s
than []
. So You now say, "s is a pointer ..." and now you go out of the parenthesis and see the []
. So you continue, "s is a pointer to an array". And that is exactly what it is. It is a pointer, which will point to the first element of an array.
Now follow the same logic and try to guess what the following will be:
int (*callme)(int a, int b)
int (*callme[10])(int a, int b)
Hint, the last one can be used to create lookup tables for functions.
Edit:
As mentioned in the comments, there is also a char
in the beginning. I have never ben able to figure out an easy way of speaking this, but is generally clear from the context. For example, in the first example, the char
defines the type of the array, while in the second example, it defines pointer. In the exercises I have posted, the int
defines the type for the return values of the functions. Generally with definitions such as these, there will be exactly one item with the undefined type. And thats how I figure out where the type goes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With