gpt4 book ai didi

c - c 中的字符串作为数组

转载 作者:行者123 更新时间:2023-11-30 18:47:14 25 4
gpt4 key购买 nike

我是 c 语言新手,我试图做一些简单的事情来了解字符串和字符数组,但我陷入了这部分代码。

 const char *words(int count) {
char *words = "words";
if(count==1) {
words[strlen(words)-1] = '\0';// segmentation fault
}
return words;
}

它的作用是当计数等于 1 时返回单词,否则返回单词。我的问题是为什么这行代码有问题,为什么我不能将字符串视为字符数组

words[strlen(words)-1] = '\0';

我尝试以不同的方式声明字符串(字符数组),例如
char *words = {'w','o','r','d','s'};但我仍然遇到段错误。

最佳答案

ISO/IEC 9899:TC3 N1256
6.7.8 初始化 - 32,示例 8 声明

char s[] = "abc", t[3] = "abc";

defines ‘‘plain’’ char array objects s and t whose elements are initialized with character string literals. This declaration is identical to

char s[] = { 'a', 'b', 'c', '\0' },
t[] = { 'a', 'b', 'c' };

The contents of the arrays are modifiable. On the other hand, the declaration

char *p = "abc";

defines p with type ‘‘pointer to char’’ and initializes it to point to an object with type ‘‘array of char’’ with length 4 whose elements are initialized with a character string literal. If an attempt is made to use p to modify the contents of the array, the behavior is undefined.

<小时/>

简而言之,您尝试修改声明为 char * Words = "words"words 指向的内容,以及字符串文字 "words " 通常存储在只读部分,这就是您获得 SEGSEV 的原因。

关于c - c 中的字符串作为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49332937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com