为什么我得到一个分段错误,当我尝试修改字符串常量? [英] Why do I get a segmentation fault when I try to modify a string constant?

查看:80
本文介绍了为什么我得到一个分段错误,当我尝试修改字符串常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string\">Why做写入字符串时,我得到一个分段错误?


我希望这个程序的输出是:ibjgsjfoet
但我得到一个分段错误。

 的#include&LT;&stdio.h中GT;
诠释的main()
{    的char * p =haifriends,* P1;
    P1 = P;
    而(* P!='\\ 0')
    ++ * P ++;
    的printf(%s%S,P,P1);
    返回0;}


解决方案

您正试图修改字符串:

 的char * p =haifriends;
++ * P;

通常,字符串被分配在非可写存储器,因此段错误。

Possible Duplicate:
Why do I get a segmentation fault when writing to a string?

I expect the output of this program to be: ibjgsjfoet But i am getting a segmentation fault.

#include <stdio.h>
int main()
{

    char *p="haifriends",*p1;
    p1=p;
    while(*p!='\0')
    ++*p++;
    printf("%s   %s",p,p1);
    return 0;

}

解决方案

You are trying to modify a string literal:

char *p="haifriends";
++*p;

Usually, string literals are allocated in non writable memory, hence the segfault.

这篇关于为什么我得到一个分段错误,当我尝试修改字符串常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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