简体   繁体   中英

Why does this cycle returns different value or nothing on same index of array

I wish to make a six character long string from the array[] array with random index generation. Sometimes different values get added to the str[] string on the same index or the same value gets added to the string but not from the right index.

For example (what the program generates):

3 = 29
d = 3
d = 0
y = 24
r = 17
x = 23

Where both "d"s should have an index of 3.

Other example:

z = 25
b = 1
o = 14
= 2
d = 3
4 = 30

Where the index 2 should return "c", but returns nothing. Thus generating only a 5 char long string

int main()
{
    char array[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r','s', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '_'};

    char str[] = "";

    srand(time(0));
    for(int i = 0; i < 6; i++)
    {
         int k = (rand() % sizeof(array));
         char c = array[k];
         printf("%c = %d \n", c, k);
         strncat(str, &c, 1);
    }

    printf("%s", str);

    return 0;
}

When you declare str you need to specify a size big enough for 6 characters plus a trailing null.

There's no need to use strcat() to assign a single character, just assign str[i] = c; . strncat() also doesn't add a null terminator if you give it a limit shorter than the source string, so it's not appropriate to use it in a loop like that.

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

#define SIZE 6

int main()
{
    char array[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r','s', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '_'};
    char str[SIZE+1];

    srand(time(0));
    int i;
    for(i = 0; i < 6; i++)
    {
         int k = (rand() % sizeof(array));
         char c = array[k];
         printf("%c = %d \n", c, k);
         str[i] = c;
    }
    str[i] = '\0'; // Add null terminator

    printf("%s", str);

    return 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