I'm trying to grasp C pointers with this small example I found in a tutorial:
#include <stdio.h>
int main() {
char vowels[] = {'A', 'E', 'I', 'O', 'U'};
char *pvowels = &vowels;
printf(pvowels);
// printf(*pvowels);
return 0;
}
If I compile this I get a warning "Initialization from incompatable pointer type" but it will still compile/run, printing AEIOU plus some random junk characters. I was also under the assumption that *pvowels would be the character at the first memory location of the vowels array and hence print an 'A' but it just segfaults instead.
My two questions are:
Why does the 1st printf print out the vowels + junk?
Why does the 2nd print not print out just an A?
When you use &vowels
you get a pointer to the array not the first element in the array. The type of &vowels
is char(*)[5]
.
To fix this problem you should either use &vowels[0]
to get a pointer to the first element, or rely on that arrays naturally decays to pointers to their first element:
char *pvowels = vowels;
The second problem is that you treat pvowels
like a string , but a string is a sequence of characters with a terminator . Since the array vowels
doesn't have this terminator the printf
call will go out of bounds and you will have undefined behavior .
As for the last problem, when you dereference a pointer you get the value of the location where it points. Because the location of the array starts with the first element of the array both &vowels[0]
and &vowels
points to the same location, so when you dereference pvowels
you get the first element of the array which is the character 'A'
. However you can't use it as the first argument for printf
because the printf
function expects it to be a string (a pointer to a zero-terminated array of characters), not a single character.
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.