gpt4 book ai didi

我可以使用 char[] 或 char* 作为函数的返回值吗?

转载 作者:太空宇宙 更新时间:2023-11-04 04:59:11 24 4
gpt4 key购买 nike

我想知道(我试过但程序卡住)是否有办法创建一个返回 char* 或 char[] 的函数,这样我就不必修改发送到功能,学习如何使我的代码更 Eloquent 。

#include <stdio.h>
#define LOW_LETTERS 97
#define CAP_LETTERS 65
#define N_LETTERS 26
#define DIFF 32
#define NUMBERS 48
#define N_DIGITS 9


void transformText ( char text[] )
{
for ( int i = 0 ; text[i] != '\0' ; i++ )
{
if ( ( text[i] >= LOW_LETTERS ) && ( text[i] <= LOW_LETTERS + N_LETTERS ) )
text[ i ] = text [ i ] - DIFF ; //same letter, but upper case
else
if ( ( text [ i ] >= CAP_LETTERS ) && ( text[i] <= CAP_LETTERS + N_LETTERS ) )
text [ i ] = text [ i ] + DIFF ; //same letter, but lower case
else
if ( text [i] >= NUMBERS && text[i] <= NUMBERS + N_DIGITS )
text[i] = '*'; //turns every number to a '*'
}

}

int main (void)
{
char text[] = "foOo123Oo44O99oO00" ;
transformText ( text ) ;
printf ( "%s\n", text ) ; //prints FOoO***oO**o**Oo**

return 0 ;
}

这就是我解决它的方法,我想我有内存泄漏的想法,不是吗?请注意,我没有修改原始字符串,这是我打算做的,而且我真的不知道将 free(newText) 放在哪里,所以它可以被识别,但仍然可用对于 main()

#include <stdio.h>
#define LOW_LETTERS 97
#define CAP_LETTERS 65
#define N_LETTERS 26
#define DIFF 32
#define NUMBERS 48
#define N_DIGITS 9
#define BUFFER 128


char* transformText ( char text[] )
{
char *newText = (char *) malloc (BUFFER) ;
for ( int i = 0 ; text[i] != '\0' ; i++ )
{
if ( ( text[i] >= LOW_LETTERS ) && ( text[i] <= LOW_LETTERS + N_LETTERS ) )
newText[ i ] = text [ i ] - DIFF ; //same letter, but upper case
else
if ( ( text [ i ] >= CAP_LETTERS ) && ( text[i] <= CAP_LETTERS + N_LETTERS ) )
newText [ i ] = text [ i ] + DIFF ; //same letter, but lower case
else
if ( text [i] >= NUMBERS && text[i] <= NUMBERS + N_DIGITS )
newText[i] = '*'; //turns every number to a '*'
else
newText[i] = text[i] ;
}

return newText ;
}

int main (void)
{
char text[] = "foOo123Oo44O99oO00" ;

printf ( "%s\n", transformText ( text ) ) ; //prints FOoO***oO**o**Oo**
return 0 ;
}

最佳答案

一般来说,是的,你有一个返回 char * 的函数是很好的,但是你需要注意一些事情,比如

  • 您需要确保不要将局部变量的地址返回给被调用的函数。这将产生在调用者中使用无效内存的问题。更好的方法是使用 malloc() 或 family 分配内存并返回指针。使用完内存后,您还需要free() 内存。
  • 如果要使用返回的指针,则需要确保返回指针的有效性。

编辑:

因此,一旦您在调用方中获得了返回的指针并完成了它的使用,您需要通过调用 free() 并传递指针来释放之前分配的内存。在你的情况下,它应该看起来像

char * res = transformText ( text );
printf ( "%s\n", res ); // use the returned pointer
free(res); // release memory
return 0 ; // done

关于我可以使用 char[] 或 char* 作为函数的返回值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42337618/

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