我无法理解由我的代码提供的与指针一起使用的输出。 有人可以帮我吗
这是我的代码,
#include <stdio.h>
void main(){
struct stype {
int x;
char *p;
};
struct stype s[ ] = {
{ 1 , "Colombo" },
{ 2 , "Gampaha" },
{ 3 , "Kalutara" },
{ 4 , "Matara" },
{ 5 , "Galle" },
};
struct stype *t;
t = s;
t++;
printf( "%d\n" , t->x );
printf( "%c\n", *( ++t->p ) );
printf( "%s\n" , t->p );
printf( "%d\n" , ( ++t )->x );
printf( "%s\n", ++t->p );
printf( "%s\n" , ++t->p );
printf( "%c\n" , *( ++t->p ) + 5 );
}
这是我得到的输出
2
a
ampaha
3
alutara
lutara
z
答案 0 :(得分:2)
下面逐行给出解释
struct stype *t ; // t is a pointer to struct
t = s ; // t will point to the array
t++; // increment t, so it will point to the
// first element i.e. s[1]
printf( "%d\n" , t->x ) ; // print s[1].x i.e 2
printf( "%c\n", *( ++t->p ) ) ; // Here the precedence rules come into play.
// The Prefix increment is in level 2 and -> operator
// is in level 1, so -> operator will be carried out first
// and then ++, t-> p will point to "Gampaha"
// and incrementing that will point
// to the next character "ampaha"
// so *(++t->p) will give 'a'
printf( "%s\n" , t->p ) ; // t->p is already incremented,
// so it will point to "ampaha".
printf( "%d\n" , ( ++t )->x ) ; // t is incremented to point to s[2]
// and x, of that is taken, so will print 3
printf( "%s\n", ++t->p ) ; // t-> p is first executed, "Kalutara",
// t->p is incremented so, "alurata" is printed.
printf( "%s\n" , ++t->p ) ; // again t-> p is first executed, "alutara",
// t->p is incremented so, "lurata" is printed.
printf( "%c\n" , *( ++t->p ) + 5 ) ; // t-> p is first executed "lutara",
// t-> p is incremented "utra" *( ++t->p ) is 'u'
// and 5 is added to that to get 'z'
答案 1 :(得分:0)
我认为您在理解printf( "%c\n" , *( ++t->p ) + 5 );
时遇到问题了吗?
*( ++t->p ) = u
u的ascii值为117。
117 + 5 = 122
z的ascii值为122。
所以,输出是z。