分配指针值

问题描述

我是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;
}

希望我在代码中的注释可以帮助您了解会发生什么。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...