分段错误反转字符串文字

Sur*_*rya 6 c

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    //char s[6] = {'h','e','l','l','o','\0'};
    char *s = "hello";       
    int i=0,m;
    char temp;

    int n = strlen(s);
    //s[n] = '\0';
    while (i<(n/2))
    {
         temp = *(s+i);       //uses the null character as the temporary storage.
         *(s+i) = *(s+n-i-1);
         *(s+n-i-1) = temp;
         i++;
    }
    printf("rev string = %s\n",s);
    system("PAUSE");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在编译时,错误是分段错误(访问冲突).请告诉我们两个定义有什么区别:

char s[6] = {'h','e','l','l','o','\0'};
char *s = "hello"; 
Run Code Online (Sandbox Code Playgroud)

小智 14

您的代码尝试修改C或C++中不允许的字符串文字如果您更改:

char *s = "hello"; 
Run Code Online (Sandbox Code Playgroud)

至:

char s[] = "hello"; 
Run Code Online (Sandbox Code Playgroud)

那么你正在修改数组的内容,文本已被复制到该数组中(相当于用单个字符初始化数组),这是可以的.


sep*_*p2k 5

如果这样做char s[6] = {'h','e','l','l','o','\0'};,则将 6 chars 放入堆栈上的数组中。当你这样做char *s = "hello";时,堆栈上只有一个指针,它指向的内存可能是只读的。写入该内存会导致未定义的行为。