【问题标题】:Assigning pointer values分配指针值
【发布时间】:2020-12-21 09:00:37
【问题描述】:

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

请尽可能详细地解释代码和输出。你会帮我很多。 提前谢谢你。

【问题讨论】:

  • 你不懂什么
  • char *p="实习";
  • 它创建一个名为p 的指针。指针p 指向一个字符串字面量,即“实习”
  • 我不明白 printf("%c\n", *p++); 的输出如何来吧。
  • p 指向“实习”,因此*p 返回I。 Affterward p 由于++ 而增加。所以现在p 指向“实习”。其余部分或多或少相同。

标签: c string pointers dereference


【解决方案1】:

这是指针算术和值算术的混淆组合,结合了前缀和后缀递增/递减。

#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;
}

我希望你代码中的 cmets 能帮助你理解发生了什么。

【讨论】:

  • 我明白了。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-13
  • 1970-01-01
  • 2015-03-20
  • 2013-12-10
  • 2016-04-19
  • 2018-11-26
相关资源
最近更新 更多