char s[] = "hello";
Declares an array of zero-terminated characters called s. Its the same as writing
char s[6] = { 'h', 'e', 'l', 'l', 'o', '\0' };
As you can see, the quotation marks are a shorthand.
char *str = s;
This declares str
to be a pointer to a character. It then makes str
point to the first character in s
. In other words, str
contains the address of the first character in s
.
int a[] = {1, 2, 3, 4, 5};
Declares an array of integers. It initializes them to the values 1-5, inclusive.
int *b = a;
Declares b
to be a pointer to an int. It then makes b
point to the first int in a
.
printf("%s\n", str);
The %s
specifier accepts the address of the first character in the string. printf
then walks from that address, printing the characters it sees, until it sees the \0
character at the end.
printf("%c\n", *str);
This prints the first character in str
. Since str
is pointing to a character (the first character in the string), then *str
should obtain the character being pointed at (the first character in the string).
printf("%c\n", *(str + 1));
This prints the second character in str
. This is the long way of writing str[1]
. The logic behind this is pointer arithmetic. If str
is the address of a character, then str + 1
is the address of the next character in the array. Since (str + 1)
is an address, it may be dereferenced. Thus, the *
obtains the character 1 character past the first character of the array.
printf("%p\n",str);
The %p
specifier expects a pointer, just like %s
would, but it does something else. Instead of printing the contents of a string, it simply prints the address the pointer is containing, in hex.
printf("%d\n",*b);
This prints the first int
in the array pointed to by b
. This is equivalent to writing b[0]
.
printf("%d",b);
b
is an int *
, not an int
, which is what %d
expects. If you were trying to print the address of the first element of the array, the specifier would be %p
, not %d
. Also, this line should not generate a compiler error. Instead, it should have been a runtime undefined behavior, since the compiler does not know what a printf
format string is.