简体   繁体   中英

How do I fill an array of random uppercase letters as a function in C?

I'm trying to write a function to fill an array with 40 random uppercase letters. I attempted to fill the array and print it but I'm not getting any output.

Thank you in advance.

#include <stdio.h>
#include <stdlib.h>

void fillS1(char y[]);

int main(int argc, const char * argv[])
{
char s1[40];
int n;

fillS1(&s1[40]);

for (n = 0; n < 41; n++) {
    printf("%s", s1);
}


return 0;
}

void fillS1(char y[40]){

int x = 1;

while (x < 41) {
    x = rand() % 26;
    x = 2 + 'A';
    x = y[x];
    x++;
}


}

I would just code

void fill_string_40(char str[])
{
   for (int i=0; i<40; i++)
     str[i] = 'A' + random() % 26;
   str[40] = (char)0; // (char)0 is equal to use '\0'
}

and use it as (eg in your main )

{ char s[41];
  fill_string_40(s);
  printf("%s\n", s);
}

Notice that you need an extra byte for the null terminating character. Ad we are assuming some ASCII compatible char encoding. A more portable way could have been

str[i] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[random() % 26];

since literal strings are constant arrays of chars.

If you code in C++, see the standard <random> header file . If you code for Linux, see random(4) and getrandom(2) , perhaps use it with srandom(3) . Read also about the Mersenne Twister

Try this, and don't forget to call srand() in the beginning of your program somewhere, ONCE.

void fillRand(char ar[], size_t len)
{
    size_t i=0;
    if (0 == len)
        return;

    for (i=0;i<(len-1);++i)
       ar[i] = (rand() % 26) + 'A';
    ar[len-1] = 0;
}       

BTW, totally not portable, as the spec does not call for 'A'..'Z' to be either sequential or contiguous, but it will probably work fine for what you need. If absolute portability was required, then the following will always work:

void fillRand(char ar[], size_t len)
{
    static const char a[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    size_t i=0;

    if (0 == len)
        return;

    for (i=0;i<(len-1);++i)
       ar[i] = a[ (rand() % (sizeof(a)-1)) ];
    ar[len-1] = 0;
}       

Will work on both normal and EBCDIC platforms. (if you don't know the difference, just use this one).

Also, you should pass address of first char while calling fillS1() . Replace fillS1(&s1[40]); with fillS1(&s1[0]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM