gpt4 book ai didi

c - 将字符附加到字符串并返回字符串

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

我正在尝试调用一个 String,根据特定条件添加一个字符,更新最长的 String 然后返回 String.

我知道,由于我要更改 String(通过添加字符),我不能使用 const char* pointer,因此我必须使用 字符数组[]

但是我也知道char array[]不能返回,只能返回指针。所以我对如何更新字符串(作为 char 数组[]),然后返回它(作为 const char* 指针)感到困惑。

 const char* longestWord(char line[])
{
int pos = 0;
char longest[250];
char ch = line[pos];
int longestLength = 0;
char current[250];
int currentLength = 0;

if(isalpha(ch) || isdigit(ch))
{
longest[longestLength] = ch;
longest[longestLength + 1] = '\0';
currentLength++;
}

pos++;
}
return longest;

最佳答案

除非 line 足够大以容纳它永远需要的东西,否则您将无法这样做。

这里最直接的解决方案是将参数放在堆上,因此使用 malloc(length_of_str) 分配它。在 longestWord 中,您可以调用 line = realloc(line, new_length) 以便为自己留出更多空间来填充字符。

返回 longest 永远不会工作,因为它在堆栈上,一旦您的方法离开,堆栈就会被释放。您也可以通过 malloc() 分配 longest 并返回该指针,在这种情况下,您只需要调用 free()不再需要时返回的指针。

关于c - 将字符附加到字符串并返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30632598/

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