1

I have to return the array b to the main program as char **. How do I do it? If I give

return b;  

it gives me an error.

In main() if I give

char **c;
c=GetRandomStrings(2,10,10);

I will get the first string. How to obtain the remaining strings?

char b[10][20];

char**  GetRandomStrings(int minimumLengthOfString, int maximumLengthOfString, int numOfStrings)
{
    static const char alphanum[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    char s[maximumLengthOfString];
    int num =0,length;

    srand((unsigned int)time(NULL));

    for (int j=0;j<numOfStrings;j++)
    {
        length = randomLength (minimumLengthOfString,maximumLengthOfString);
        for (int i = 0; i < length; ++i)
        {
            num = rand() % (sizeof(alphanum) - 1);
            s[i] = alphanum[num];
        }

       s[length] = '\0';
       strcpy(b[j],s);
    }

    for (int j=0;j<numOfStrings;j++)
    {
       printf("\n\n%s",b[j]);
    }
    return b;
}

int randomLength(int minimumLength, int maximumLength)
{
    return (rand()%(maximumLength - minimumLength) + minimumLength);
}
4
  • Well you're not actually returning anything? Commented Sep 3, 2014 at 7:41
  • 1
    Besides that, if you intend to return b, then consider that you will return a pointer to a local variable, which leads to undefined behavior, and also that b is an array of arrays of characters, which is not the same as a pointer to a pointer to character. Commented Sep 3, 2014 at 7:43
  • b should not be global, you should malloc it within GetRandomStrings() Commented Sep 3, 2014 at 9:27
  • type of b is char (*)[20], not char**. but There is no need to return a global variable. Commented Sep 3, 2014 at 10:05

1 Answer 1

1

When you try to return b from your function you will get warning such as-

warning: return from incompatible pointer type [enabled by default]
warning: function returns address of local variable [enabled by default]

Which leads to undefined behavior!

Try to make b as a pointer to pointer to character and allocate memory for it, Get the strings and return the address of b. This time when you leave the function b wont get affected.

And finally don't forget to free the allocated memory!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.