相关疑难解决方法(0)

char s []和char*s有什么区别?

在C中,可以在声明中使用字符串文字,如下所示:

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

或者像这样:

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

那么区别是什么呢?我想知道在编译和运行时的存储持续时间实际发生了什么.

c string constants char

495
推荐指数
6
解决办法
33万
查看次数

为什么在写入用"char*s"而不是"char s []"初始化的字符串时会出现分段错误?

以下代码在第2行接收seg错误:

char *str = "string";
str[0] = 'z';  // could be also written as *str = 'z'
printf("%s\n", str);
Run Code Online (Sandbox Code Playgroud)

虽然这非常有效:

char str[] = "string";
str[0] = 'z';
printf("%s\n", str);
Run Code Online (Sandbox Code Playgroud)

经过MSVC和GCC测试.

c c-strings segmentation-fault

277
推荐指数
10
解决办法
7万
查看次数

为什么这个字符串反转C代码会导致分段错误?

我正在尝试编写代码来反转字符串(我只是想在C编程和指针操作方面做得更好),但我无法弄清楚为什么我会遇到分段错误:

#include <string.h>

void reverse(char *s);

int main() {
    char* s = "teststring";
    reverse(s);

    return 0;
}

void reverse(char *s) {
    int i, j;
    char temp;

    for (i=0,j = (strlen(s)-1); i < j; i++, j--) {
        temp = *(s+i);     //line 1
        *(s+i) = *(s+j);   //line 2
        *(s+j) = temp;     //line 3
    }
}
Run Code Online (Sandbox Code Playgroud)

它是第2行和第3行导致分段错误.我知道可能有更好的方法来做到这一点,但我有兴趣找出我的代码中特别导致分段错误的内容.

更新:我已根据要求包含了调用函数.

c string segmentation-fault

29
推荐指数
2
解决办法
6610
查看次数

标签 统计

c ×3

segmentation-fault ×2

string ×2

c-strings ×1

char ×1

constants ×1