Why can't I use this code to overwrite a string?

后端 未结 4 898
刺人心
刺人心 2020-12-11 11:50

Code:

#include \"stdio.h\"
#include \"string.h\"

int main()
{
  char *p = \"abc\";
  printf(\"p is %s \\n\", p);
  return 0;
}

O

4条回答
  •  -上瘾入骨i
    2020-12-11 12:08

    In your code:

    char *p="abc";
    

    p points to a string literal - you are not allowed to change string literals, which is what your call to strcpy is trying to do. Instead, make p an array:

    char p[] = "abc";
    

    which will copy the literal into something that you are allowed to modify.

提交回复
热议问题