分配指针值
Assigning pointer values
我是 C 语言的初学者,不理解指针、字符串等可能很简单的概念
源码如下
#include<stdio.h>
int main(void){
char *p="Internship ";
printf("%s\n", p);
printf("%c\n", *p++);
printf("%c\n", *p+2);
printf("%c\n", *(p+6));
printf("%c\n", *++p);
printf("%c\n", *p--);
printf("%c\n", *(p+5));
printf("%c\n", *p);
return 0;
}
输出为
Internship
I
p
h
t
t
s
n
请尽可能详细地解释代码和输出。你会帮助我很多。
提前谢谢你。
这是指针算术和值算术的混淆组合,结合了前缀和后缀 increment/decrement。
#include<stdio.h>
int main(void){
char *p="Internship "; /* creates a pointer p that points to the memory area
that contains the String Internship */
printf("%s\n", p); /* This prints the string that p points to */
printf("%c\n", *p++); /* This prints the character that p points to (I)
and then increments the address contained in p */
printf("%c\n", *p+2); /* This prints the character that p points to (n),
but adds 2 to the value 'n' + 2 = 'p' (in ASCII) */
printf("%c\n", *(p+6)); /* This prints the character 6 ahead of what p points
to (h) */
printf("%c\n", *++p); /* This prints the character the successor of p's value
points to (t). p is incremented */
printf("%c\n", *p--); /* This prints the character that p points to (t), and
then decrements the value of p */
printf("%c\n", *(p+5)); /* This prints the character 5 ahead of the character
p points to (s), but doesn't change p */
printf("%c\n", *p); /* This again prints the character p points to (n) */
return 0;
}
我希望我在你的代码中的评论能帮助你理解发生了什么。
我是 C 语言的初学者,不理解指针、字符串等可能很简单的概念
源码如下
#include<stdio.h>
int main(void){
char *p="Internship ";
printf("%s\n", p);
printf("%c\n", *p++);
printf("%c\n", *p+2);
printf("%c\n", *(p+6));
printf("%c\n", *++p);
printf("%c\n", *p--);
printf("%c\n", *(p+5));
printf("%c\n", *p);
return 0;
}
输出为
Internship
I
p
h
t
t
s
n
请尽可能详细地解释代码和输出。你会帮助我很多。 提前谢谢你。
这是指针算术和值算术的混淆组合,结合了前缀和后缀 increment/decrement。
#include<stdio.h>
int main(void){
char *p="Internship "; /* creates a pointer p that points to the memory area
that contains the String Internship */
printf("%s\n", p); /* This prints the string that p points to */
printf("%c\n", *p++); /* This prints the character that p points to (I)
and then increments the address contained in p */
printf("%c\n", *p+2); /* This prints the character that p points to (n),
but adds 2 to the value 'n' + 2 = 'p' (in ASCII) */
printf("%c\n", *(p+6)); /* This prints the character 6 ahead of what p points
to (h) */
printf("%c\n", *++p); /* This prints the character the successor of p's value
points to (t). p is incremented */
printf("%c\n", *p--); /* This prints the character that p points to (t), and
then decrements the value of p */
printf("%c\n", *(p+5)); /* This prints the character 5 ahead of the character
p points to (s), but doesn't change p */
printf("%c\n", *p); /* This again prints the character p points to (n) */
return 0;
}
我希望我在你的代码中的评论能帮助你理解发生了什么。