gpt4 book ai didi

c - 如何修改 C 中字符串数组中的单个字符?

转载 作者:太空宇宙 更新时间:2023-11-04 01:48:31 25 4
gpt4 key购买 nike

我有一个 char** 类型的数组,我需要修改其字符串中的单个字符。它给了我一个段错误。其中的一个最小样本:

  char *a[1] = { "Test" };
printf("%c\n", a[0][2]); //Output: 's'
a[0][2] = 'e'; //Segfault here
printf("%c\n", a[0][2]);

我知道将字符串声明为字符数组而不是 char 指针可以更改单个字符,如下所示:

char c[] = "Str";
c[1] = 'r';
printf("%s\n", c);

但我不清楚如何使后一种技术在前一种情况下起作用,或者至少,如何能够更改包含在数组中的字符串中的单个字符,无论采用何种方式。

最佳答案

如果你正在寻找替代品,这可以是一个

char *a[2];
a[0]= strdup("Test");
a[1]= strdup("Thisworked");
...
a[0][2]='e'; // works.
...
free(a[0]);
free(a[1]);

您可以复制该字符串以便对其进行编辑。试图修改它是未定义的行为。在您的情况下,未定义的行为会导致段错误。来自 standard §6.4.5¶7

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

同样,您可以像以前那样做同样的事情——您可以用文字字符串初始化一个 char 数组——它是可修改的,因为正在创建字符串的副本。 (它没有像字符串文字那样的不可修改性约束)。此外,如果您知道要使用的所有文字都有 MAXLETTER 个字符,那么您可以这样做

#defined MAXLETTER 20
char c[][MAXLETTER+1]={"Test","Helloworld!"};

Standard提到它 §6.7.9¶14

An array of character type may be initialized by a character string literal or UTF-8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

关于c - 如何修改 C 中字符串数组中的单个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48513013/

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