Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 程序中的运行时错误_C_Pointers_Runtime Error_Increment - Fatal编程技术网

C 程序中的运行时错误

C 程序中的运行时错误,c,pointers,runtime-error,increment,C,Pointers,Runtime Error,Increment,我无法理解为什么代码没有运行。问题出在语句++*p++中,但问题出在哪里?p指向常量字符串文字*p=“abcd”通过执行++*p++您试图修改字符串“”abcd””,例如,字符串中的a将增量为'b',因为++*p是未定义的行为(常量字符串不能更改)。它可能会导致分段错误 int main() { char *p="abcd"; while(*p!='\0') ++*p++; printf("%s",p); return 0; } p指向一个只读段,不能像这里那样递增p cha

我无法理解为什么代码没有运行。问题出在语句
++*p++
中,但问题出在哪里?

p
指向常量字符串文字
*p=“abcd”通过执行
++*p++
您试图修改字符串“
”abcd”
”,例如,字符串中的
a
将增量为
'b'
,因为
++*p
是未定义的行为(常量字符串不能更改)。它可能会导致分段错误

int main()
{
  char *p="abcd";
  while(*p!='\0') ++*p++;
  printf("%s",p);
  return 0;
}
p指向一个只读段,不能像这里那样递增p

 char *p="abcd";
考虑一下
foo
bar
之间的差异
foo
是一个初始化为指向为字符串文本保留的内存的指针
bar
是一个数组,它自己的内存被初始化为字符串文字;它的值在初始化过程中从字符串文本复制而来。可以修改
bar[0]
等,但不能修改
foo[0]
。因此,您需要一个数组声明

但是,不能增加数组声明;这是指针变量或整数变量的操作。此外,循环在打印前会更改
p
指向的位置,因此需要将字符串的原始位置保留在某个位置。因此,还需要一个指针或整数声明

考虑到这一点,将代码更改为以下内容似乎是个好主意:

char *foo = "abcd";
char bar[] = "abcd";

下一个错误是当
while()
终止并且您尝试
printf(“%s”,p”)时,您将
p
移位到“\0”这不会打印任何东西。最好解释一下你对这个程序的期望,这样写答案的人就可以告诉你如何修复它。我希望输出是-bcdei没有得到它。。。为什么我不能增加p?@Ceres111答案中的陈述不正确。。。您可以增加
p
。您不能增加的是
*p
,因为正如Uday所说,
p
指向只读内存。非常感谢。现在我明白了。这意味着*p可以增加,不是吗
while(*p!='\0') ++*p++;
//char *p="abcd";//"string" is const char, don't change.
  char str[]="abcd";//is copied, including the '\0' to reserve space
  char *p = str;
  while(*p!='\0') ++*p++;
//printf("%s",p);//address pointing of 'p' has been changed
  printf("%s",str);//display "bcde"
char *foo = "abcd";
char bar[] = "abcd";
int main()
{
    char str[] = "abcd";

    /* Using a pointer variable: */
    for (char *ptr = str; *ptr != '\0'; ++*ptr++);

    /* Using a size_t variable: */
    for (size_t x = 0; str[x] != '\0'; str[x++]++);

    printf("%s", str);
    return 0;
}