为什么我不能用这个code覆盖一个字符串? [英] Why can't I use this code to overwrite a string?

查看:133
本文介绍了为什么我不能用这个code覆盖一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

code

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

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

输出

p is abc


code

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

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

输出

Segmentation fault (core dumped)

有人能解释为什么出现这种情况?

Could someone explain why this happens?

推荐答案

在您的code:

char *p="abc";

p指向字符串文本 - 你不能改变字符串文字,这是你对strcpy的呼叫尝试做的。相反,使P上数组:

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.

这篇关于为什么我不能用这个code覆盖一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆