常量字符串出现的segmentation fault(core dumped)

来源:互联网 发布:电魂网络 编辑:程序博客网 时间:2024/05/22 01:53

问题描述:

//错误写法,常量字符串,在c语言中不可更改char *str = "I am a student.";//正确写法,字符串数组,可以作为变量,可以更改,更改不会发生错误   char str[15] = "I am a student.";

一、看代码main函数

#include <stdio.h>#include <string.h>//头尾对调int ReverseString(char* s, int head, int last){    int count = 0;    printf("str = %s\n", s);    while (head< last)    {        //将头存储在临时变量中        char t = s[head];        //将尾部赋值给头,头部++        s[head++] = s[last];        //将头赋值到尾部,尾部--        s[last--] = t;        printf("count = %d\n", count);    }}int main(){    int len = 0;    //错误写法,常量字符串,在c语言中不可更改    char *str = "I am a student.";    len = strlen(str) - 1;    //常量字符串在该函数不可更改,出现错误    ReverseString(str, 0, len);    printf("str = %s\n", str);}

二、正确写法:

//数组可作为变量字符串,可以更改
char str[16] = “I am a student”;

以下为完整代码

#include <stdio.h>#include <string.h>//头尾对调int ReverseString(char* s, int head, int last){    int count = 0;    printf("str = %s\n", s);    while (head< last)    {        //将头存储在临时变量中        char t = s[head];        //将尾部赋值给头,头部++        s[head++] = s[last];        //将头赋值到尾部,尾部--        s[last--] = t;        printf("count = %d\n", count);    }}int main(){    int len = 0;    char str[15] = "I am a student.";    len = strlen(str) - 1;    ReverseString(str, 0, len);    printf("str = %s\n", str);}
0 0