我一直在做一个…有趣的。。。任务我被要求使用指针修改字符数组。
我知道:
*char="某物"//是文字,无法修改。
char[]="某物"//可以修改
但是:呢
main.c
------
static char* stringlist01[] =
{
"thiy iy a ytring",
"this is also a string, unlike the first string",
"another one, not a great one, and not really like the last two.",
"a third string!",
NULL,
};
int main()
{
int ret = 9999;
printf("////TEST ONE////nn");
ret = changeLetterInString(stringlist01[0]);
printf("Return is: %dnn", ret);
printf("Stringlist01[0] is now: %sn", stringlist01[0]);
}
和
changeLetterInString.c
----------------------
int changeLetterInString(char *sentence)
{
if (sentence != NULL)
{
// TODO
// Need to change "thiy iy a ytring"
// into "this is a string"
// and save into same location so
// main.c can see it.
}
success = 0; // 0 is Good
return success;
}
到目前为止,我已经尝试过:
for (char* p = sentence; *p; ++p)
{
if (*p == 'y')
{
*p = 's';
}
}
我试过:
sentence[0] = 't'
sentence[1] = 'h'
sentence[2] = 'i'
sentence[3] = 's' // and so on...
但两者都不起作用。
如有任何帮助和/或见解,我们将不胜感激。
这两种符号之间有细微的区别:
char string[] = "Hello World";
// vs
char* string = "Hello World";
他们看起来很相似,对吧?然而,它们是不同的。第一个是字符数组,而第二个是指向字符数组的指针。
默认情况下,任何字符串文字都将始终为const
。没有办法。试图修改字符串文字通常会导致segfault。
您的代码包含指向字符数组的指针数组。由于包含对常量字符串文字的指针引用,因此无法修改它们。为了修改它们,您需要将它们转换为一个数组,就像第一个示例中那样。这将把字符串文字转换为可以修改的字符数组,而不是指向无法修改的内存的指针。
char strs[][] = {
"Hello",
"World"
}; // transforms the string literals into character arrays
strs[0][0] = 'X'; // valid
而这不会编译,并导致未定义的行为
char* strs[] = {
"Hello",
"World",
};
strs[0][0] = 'X'; // trying to modify a pointer to a constant string literal, undefined