How do I return a variable size string from a func

2019-08-18 11:20发布

I need a working code for a function that will return a random string with a random length.

What I want to do would be better described by the following code.

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

For this, I am strictly forbidden to use any other include than stdio.h. Edit: This project will be adapted to be compiled for a PIC Microcontroller, hence I cannot use malloc() or such stuff. The reason why I use stdio.h here, is for me to be able to inspect the output using GCC.

Currently, this code gives this error.-
“warning: function returns address of local variable [enabled by default]”

Then, I thought this could work.-

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

But it only prints a bunch of nonsense characters.

5条回答
别忘想泡老子
2楼-- · 2019-08-18 11:39

If you are not allowed to use malloc you'll have to declare an array that can be the maximum possible size at file scope and fill it with random characters.

#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;
}
查看更多
地球回转人心会变
3楼-- · 2019-08-18 11:48

It points to nonsense characters because you are returning local address. char word[random-length]; is defined local to char *getRandomString(char *string)

Dynamically allocate the string with malloc, populate string, and return the returned address by malloc. This returned address is allocated from the heap and will be allocated until you do not manually free it (or the program does not terminate).

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

After you have done with the allocated string, remember to free the string.

Or another thing can be done, if you cannot use malloc which is define the local string in the getRandomString as static which makes the statically declared array's lifetime as long as the program runs.

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

Or simply make the char word[128]; global.

查看更多
爷的心禁止访问
4楼-- · 2019-08-18 11:55

There are three common ways to do this.

  1. Have the caller pass in a pointer to (the first element of) an array into which the data is to be stored, along with a length parameter. If the string to be returned is bigger than the passed-in length, it's an error; you need to decide how to deal with it. (You could truncate the result, or you could return a null pointer. Either way, the caller has to be able to deal with it.)

  2. Return a pointer to a newly allocated object, making it the caller's responsibility to call free when done. Probably return a null pointer if malloc() fails (this is always a possibility, and you should always check for it). Since malloc and free are declared in <stdlib.h> this doesn't meet your (artificial) requirements.

  3. Return a pointer to (the first element of) a static array. This avoids the error of returning a pointer to a locally allocated object, but it has its own drawbacks. It means that later calls will clobber the original result, and it imposes a fixed maximum size.

None if these is an ideal solution.

查看更多
做个烂人
5楼-- · 2019-08-18 11:58

As I understand, malloc is not an option.

Write a couple of functions to a) get a random integer (strings length), and b)a random char.

Then use those to build your random string.

For example:

//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';
}
查看更多
叼着烟拽天下
6楼-- · 2019-08-18 11:59

Both of your examples are returning pointers to local variables - that's generally a no-no. You won't be able to create memory for your caller to use without malloc(), which isn't defined in stdio.h, so I guess your only option is to make word static or global, unless you can declare it in main() and pass the pointer to your random string function to be filled in. How are you generating random numbers with only the functions in stdio.h?

查看更多
登录 后发表回答