如何从函数返回可变大小的字符串?

我需要一个函数的工作代码,它将返回一个随机长度的随机字符串。

我想要做的事情将通过以下代码更好地描述。

char *getRandomString() { char word[random-length]; // ...instructions that will fill word with random characters. return word; } void main() { char *string = getRandomString(); printf("Random string is: %s\n", string); } 

为此,我严格禁止使用除stdio.h之外的任何其他包含。 编辑:这个项目将适合为PIC微控制器编译,因此我不能使用malloc()或类似的东西。 我在这里使用stdio.h的原因是我能够使用GCC检查输出。

目前,此代码给出了此错误.-
“warning:function返回局部变量的地址[默认启用]”

然后,我认为这可行.-

 char *getRandomString(char *string) { char word[random-length]; // ...instructions that will fill word with random characters. string = word; return string; } void main() { char *string = getRandomString(string); printf("Random string is: %s\n", string); } 

但它只会打印出一堆无意义的字符。

有三种常见的方法可以做到这一点。

  1. 让调用者传入指向数据存储到的数组(的第一个元素)的指针,以及一个长度参数。 如果要返回的字符串大于传入的长度,则表示错误; 你需要决定如何处理它。 (你可以截断结果,或者你可以返回一个空指针。无论哪种方式,调用者都必须能够处理它。)

  2. 返回一个指向新分配对象的指针,使调用者有责任在完成后调用free 。 如果malloc()失败,可能会返回一个空指针(这总是有可能,你应该总是检查它)。 由于mallocfree中声明,因此不符合您的(人工)要求。

  3. 返回指向静态数组(的第一个元素)的指针。 这避免了将指针返回到本地分配的对象的错误,但它有其自身的缺点。 这意味着以后的调用会破坏原始结果,并且它会施加固定的最大大小。

没有,如果这些是理想的解决方案。

它指向无意义的字符,因为您返回本地地址。 char word[random-length];char *getRandomString(char *string)本地定义

使用malloc动态分配字符串,填充字符串,并通过malloc返回返回的地址。 此返回的地址是从堆中分配的,并将被分配,直到您不手动释放它(或程序不终止)。

 char *getRandomString(void) { char *word; word = malloc (sizeof (random_length)); // ...instructions that will fill word with random characters. return word; } 

完成分配的字符串后,请记住释放字符串。

或者可以做另外的事情,如果你不能使用malloc ,它将getRandomString的本地字符串定义为static ,只要程序运行就会生成静态声明的数组的生命周期。

 char *getRandomString(void) { static char word[LENGTH]; // ...instructions that will fill word with random characters. return word; } 

或者简单地制作char word[128]; 全球。

据我了解,malloc不是一个选项。

写一些函数来a)得到一个随机整数(字符串长度),和b)一个随机字符。

然后使用它们来构建随机字符串。

例如:

 //pseudocode static char random_string[MAX_STRING_LEN]; char *getRandomString() { unsigned int r = random_number(); for (i=0;i 

如果不允许使用malloc ,则必须在文件范围内声明一个可能是最大可能大小的数组,并用随机字符填充它。

 #define MAX_RANDOM_STRING_LENGTH 1024 char RandomStringArray[MAX_RANDOM_STRING_LENGTH]; char *getRandomString(size_t length) { if( length > ( MAX_RANDOM_STRING_LENGTH - 1 ) ) { return NULL; //or handle this condition some other way } else { // fill 'length' bytes in RandomStringArray with random characters. RandomStringArray[length] = '\0'; return &RandomStringArray[0]; } } int main() { char *string = getRandomString(100); printf("Random string is: %s\n", string); return 0; } 

你的两个例子都返回指向局部变量的指针 – 这通常是禁止的。 如果没有在stdio.h定义的malloc() ,你将无法为调用者创建内存,所以我想你唯一的选择是使word static或global,除非你可以在main()声明它main()并将指针传递给你要填写的随机字符串函数。你如何只用stdio.h的函数生成随机数?