gpt4 book ai didi

c - C语言中如何返回一个指向字符串的指针

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

我尝试开发一个函数,它接受字符串反转字母并返回指向字符串的指针。

char *reverseStr(char s[])
{
printf("Initial string is: %s\n", s);
int cCounter = 0;
char *result = malloc(20);

while(*s != '\0')
{
cCounter++;
s++;
}
printf("String contains %d symbols\n", cCounter);

int begin = cCounter;

for(; cCounter >= 0; cCounter--)
{
result[begin - cCounter] = *s;
s--;
}
result[13] = '\0';
return result;
}

在主函数中,我调用该函数并尝试以这种方式打印结果:

int main()
{
char testStr[] = "Hello world!";
char *pTestStr;

puts("----------------------------------");
puts("Input a string:");
pTestStr = reverseStr(testStr);
printf("%s\n", pTestStr);
free(pTestStr);
return 0;
}

但是结果出乎意料,没有反向字符串。我有什么错?

最佳答案

共享代码中有多个错误,主要是 -

  • s++;将指针移动到'\0'。应带回 1 个单位通过输入 s-- 指向实际字符串。否则,复制的将以“\0”开头,这将使其成为空字符串。
  • 魔数(Magic Number) 20 和 13。在 malloc() 中,1 + s 的长度应该是足够,而不是 20。对于 13,只需向前移动一个单位并放置 '\0'

但是,使用string.hfunctions()这可以非常简单。但我认为你这样做是为了学习。

因此,不使用 string.h lib function() 更正后的代码应如下所示:

char *reverseStr(char s[])
{
printf("Initial string is: %s\n", s);

int cCounter = 0;
while(*s != '\0')
{
cCounter++;
s++;
}
s--; //move pointer back to point actual string's last charecter

printf("String contains %d symbols\n", cCounter);

char *result = (char *) malloc(sizeof(char) * ( cCounter + 1 ));
if( result == NULL ) /*Check for failure. */
{
puts( "Can't allocate memory!" );
exit( 0 );
}

char *tempResult = result;
for (int begin = 0; begin < cCounter; begin++)
{
*tempResult = *s;
s--; tempResult++;
}
*tempResult = '\0';
//result[cCounter+1] = '\0';
return result;
}

从主调用

int main()
{
char testStr[] = "Hello world!";
char *pTestStr;

puts("----------------------------------");
puts("Input a string:");
pTestStr = reverseStr(testStr);
printf("%s\n", pTestStr);
free(pTestStr);
}

输出

----------------------------------
Input a string:
Initial string is: Hello world!
String contains 12 symbols
!dlrow olleH

根据 WhozCraig 建议,仅使用指针算术 -

char *reverseStr(const char s[])
{
const char *end = s;
while (*end)
++end;

char *result = malloc((end - s) + 1), *beg = result;
if (result == NULL)
{
perror("Failed to allocate string buffer");
exit(EXIT_FAILURE);
}

while (end != s)
*beg++ = *--end;
*beg = 0;

return result;
}

关于c - C语言中如何返回一个指向字符串的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52492501/

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