69,374
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
int main()
{
char notes[]="See you at the snack bar.";
char * ptr;
ptr=notes;
puts(++ptr);
notes[7]='\0';
puts(++ptr);
return 0;
}
#include <stdio.h>
int main()
{
char notes[] = "See you at the snack bar.";
char * ptr;
ptr = notes;
puts(++ptr);
notes[7] = '\0';
puts(++ptr);
return 0;
}
//ee you at the snack bar.
//e you
char notes[]="See you at the snack bar.";
这一句,字面串"See you at the snack bar."在程序转换阶段先是在末尾添加一个空字符'\0',然后用于初始化一个不可见的静态数组。最后,C的实现用这个数组的内容初始化数组notes。
char * ptr;
ptr = notes;
这两句,数组notes自动转换为指向其第一个元素的指针,并将这个指针赋给ptr。也就是说,ptr现在指向数组notes的首元素,也就是notes [0]。
puts(++ptr);
这一句,puts函数要求一个字符串。字符串是一个字符的序列,且以第一个遇到的空字符('\0')终止。字符串包括单字节字符的序列和多字节字符的序列,但应与宽字符的序列相区别。
不管怎么说,因为在传递给puts函数之前,表达式++ptr的效果是指向数组notes的第二个元素(notes [1]),所以输出的是
ee you at the snack bar.
notes[7]='\0';
这一句,将数组的7号元素修改为空字符'\0'。此时,数组notes的元素是
See you\0at the snack bar.
puts(++ptr);
这一句,在进入puts函数之前,表达式++ptr的效果是指向数组notes的第三个元素(notes [2]),我们知道,puts函数输出一个字符串,但是,因为前面已经在数组中加入一个空字符'\0',所以它指向的串,以入puts函数的输出实际上是
e you
以上的关键是搞清楚数组、指针和字符串这几个概念。再来看另一个例子:
char keywords [] = "if\0else\0switch\0while";
这是一个数组,从字符串的角度来看,它包含了4个字符串,可以这样输出它们:
puts (keywords);
puts (keywords + 3);
puts (keywords + 8);
puts (keywords + 15);