Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char * function in C

Tags:

c

I am currently trying to use a random string generator to produce a string. It looks like this:

char *randstring(int length) {

    static char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-#'?!";        
    char *randomString = NULL;
    int n = 0;
    if (length) {
        randomString = malloc(sizeof(char) * (length +1));

        if (randomString) {            
            for (n = 0;n < length;n++) {            
                int key = rand() % (int)(sizeof(charset) -1);
                randomString[n] = charset[key];
            }

            randomString[length] = '\0';
        }
    }
    return randomString;
}

I am trying to call it like this:

srand(time(NULL));
int r = rand()%1000;
char *string[1000];
&string = randomstring(r);

But when I do this, I get the following error:

error: invalid lvalue in assignment. 

I have looked online but I can not figure out why this is not working. Any suggestions? It has to do with the pointer, I assume.

like image 830
user081608 Avatar asked Jan 30 '26 21:01

user081608


1 Answers

Most likely, the correct code is:

char *string = randomstring(52);

If for some reason you wanted to keep the array of character pointers, you could also do:

char *string[1000];
string[0] = randomstring(102);
like image 181
Bill Lynch Avatar answered Feb 01 '26 13:02

Bill Lynch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!