递增指针时的模糊行为

Sur*_*non 1 c pointers

#include<stdio.h>
main()
{

        char c = 'R';
        printf("%c\n",c);
        c++;
        printf("%c\n",c);
        char *ptr ="Ramco Systems";
        printf("%c\n",(*ptr));
        (*ptr)++;
        printf("%d\n",(*ptr));

}
Run Code Online (Sandbox Code Playgroud)

第一,第二,第三printf的输出是'R','S'和'R'(如预期的那样).但行"(*ptr)++;" 给运行时错误.有人可以解释原因吗?

Cam*_*Cam 5

原因是因为指向的内存ptr是在编译时设置的并且是不可修改的.

因此,访问第一个字符*ptr是很好并返回R,但尝试增加第一个字符会产生运行时错误,因为您不允许修改在编译时提供的字符串.

要扩展下面的Seg Fault评论,编写代码的更好方法是:

const char *ptr ="Ramco Systems"; //pointer to const char
(*ptr)++; // yields compiletime error because *ptr is a const char
Run Code Online (Sandbox Code Playgroud)

请注意,在这个新代码中,声明的指针类型更准确,因此编译器能够在第二行给出编译时错误(比运行时错误好得多).