Question about char pointers
I am confused with this program.
#include <stdio.h>
int main(void)
{
char* ptr="MET ADSD";
*ptr++;
printf("%c\n", ptr);
ptr++;
printf("%c\n", ptr);
}
Here's the output.
ET ADSD
T ADSD
My question is how does the pointe开发者_高级运维r display the rest of the characters?
You are passing a wrong combination of parameters to printf
: the %c
format specification requires a char
parameter, not a char*
. So the result is undefined - in your case printf
seems to print the whole char array, but this is just by pure chance. Use either
printf("%c\n", *ptr);
or
printf("%s\n", ptr);
You are actually trying to print as a char %c
a pointer value char*
. This is false. But then, I really don't understand why it prints all the chars. Are you sure you didn't use %s
instead of %c
?
The * operator as lower precedence over the ++ operator. Thus in your example the both lines
*ptr++;
ptr++;
have the same effect.
And you are using the wrong types in your printf statement.
Change
printf("%c\n", ptr);
to
printf("%s\n", ptr);
or
printf("%c\n", *ptr);
depending on what you want to output.
Btw, turning on compiler warnings helps in that case. E.g. the GCC prints:
d.c: In function ‘main’:
d.c:7: warning: value computed is not used
d.c:8: warning: format ‘%c’ expects type ‘int’, but argument 2 has type ‘char *’
d.c:11: warning: format ‘%c’ expects type ‘int’, but argument 2 has type ‘char *’
d.c:12: warning: control reaches end of non-void function
In C a string is a array of chars, and an array is simply a pointer to the first location of memory of the array. So defining
char* ptr="MET ADSD";
you are declaring and initializing an array of chars, a string, by using a pointer to char,
The next trick comes if you consider this two factors:
- pointers arithmetic in that using the operator
++
on a pointer increments its value, the memory address it is pointing to - char size which is almost everywhere 1 byte
So you are scaling the array along of two positions, and you print that by using %s
and passing the pointer to it
EDIT I guess you put %c mistakenly in the example
If you are expecting 'E' as first and 'T' as second output. Give it like
#include <stdio.h>
int main(void)
{
char* ptr="MET ADSD";
*ptr++;
printf("%c\n", *ptr);
ptr++;
printf("%c\n", *ptr);
}
printf( ..., ptr) is passing the pointer, not the char it points to. The correct version of the program would be:
#include <stdio.h>
int main(int argc, char* argv[])
{
const char* ptr = "MET ADSD";
ptr++;
printf("%c\n", *ptr);
ptr++;
printf("%c\n", *ptr);
return 0;
}
which will print
E
T
The output you are seeing makes no sense unless you are using %s. - %c is going to convert the value of ptr into an integer, truncate the int to 8bits (the width of a char), and print that character to the output. Not a string of characters.
精彩评论