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

时间:2011-08-25 17:40:06

标签: c pointers c-strings character-arrays

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

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

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);
}

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

5 个答案:

答案 0 :(得分:4)

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

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

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

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

  4. 如果这些是理想的解决方案,则无。

答案 1 :(得分:2)

它指向无意义的字符,因为您正在返回本地地址。 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;
}

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

或者可以做另外的事情,如果你不能使用mallocgetRandomString中的本地字符串定义为static,这使得静态声明的数组的生命周期与程序一样长运行。

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

或者只是将char word[128];全局。

答案 2 :(得分:0)

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

答案 3 :(得分:0)

据我了解,malloc不是一种选择。

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

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

例如:

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

    for (i=0;i<r;i++){
        random_string[i] = random_char();
    }

    random_string[r-1] = '\0';
}

答案 4 :(得分:0)

如果不允许使用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;
}
相关问题