0

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

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

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检查输出。

目前,此代码给出此错误。-
“警告:函数返回局部变量的地址[默认启用]”</p>

然后,我认为这可以工作。-

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

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

4

5 回答 5

4

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

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

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

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

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

于 2011-08-25T17:49:31.633 回答
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;
}

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

或者可以做另一件事,如果你不能使用在asmalloc中定义本地字符串,只要程序运行,它就会使静态声明的数组的生命周期保持不变。getRandomStringstatic

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

或者干脆使char word[128];全局。

于 2011-08-25T17:44:23.520 回答
0

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

于 2011-08-25T17:45:47.653 回答
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';
}
于 2011-08-25T17:48:08.667 回答
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;
}
于 2011-08-25T17:48:59.853 回答