如何解决分配指针值
我是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
请尽可能详细地解释代码和输出。你会帮我很多忙。 预先谢谢你。
解决方法
这是指针算术和值算术的混乱组合,加上前缀和后缀的增/减。
#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;
}
希望我在代码中的注释可以帮助您了解会发生什么。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。