Reputation: 90
I'm currently trying to learn C, with some prior experience in Python and pointer arithmetic is really confusing me right now.
#include <stdio.h>
int main()
{
char *s[] = {"String1", "Literal2", "Pointers3"};
printf("%c", s[1]+1);
return 0;
}
Why does it print m
instead of i
?
When I replace the format string with %s
it does what I expect and prints out iteral2
(Go to the 0th index of the 1st string literal then move 1 memory adress forward and print the rest).
How does this work, why does it print out a seemingly arbitrary character instead of the 1st(or 1th?) index when I use the %c
format string.
Upvotes: 0
Views: 42
Reputation: 1
#include <stdio.h>
int main() {
const char *s[] = {"String1", "Literal2", "Pointers3"};
printf("%c", s[1][1]);
return 0; }
Also i think you should make s[] constant as it's deprecated.
Upvotes: 0
Reputation: 62005
The %c
format specifier expects a character, not a pointer to a character. The expression s[1]
evaluates to a pointer to a character, pointing to "Literal2", and the expression s[1]+1
also evaluates to a pointer to a character, pointing to "iteral2".
So, you are passing printf()
a pointer to a character, and you are telling it to print a character. So, what is happening is that the pointer is being re-interpreted as a character, and the output is garbage.
If you insert a character into "String1", (making it, say, "String11",) then everything will be moved upwards in memory by one location, so the value of the pointer will be greater by 1, and so it might print n
instead of m
.
To obtain a character, when all you have is a pointer to a character, you need to dereference the pointer. So, that would be "%c", *(s[1]+1)
.
Upvotes: 1