0

I have written the following program:

char name[100], firstDigits[13], cards[5000][16];

srand(1019336);
int i, j;
char c = '0';
for(i=0;i<13;i++){
    c = '0' + (rand() % 43);
    while(c > 57 && c < 65){
        c = '0' + (rand() % 43);
    }
    firstDigits[i] = c;

}
printf("%s \n", firstDigits);
for(i=0;i<5;i++){
    for(j=0;j<13;j++){
        cards[i][j] = firstDigits[j];
    }
}
for(i=0;i<5;i++){

    for(j=13;j<16;j++){
        c = '0' + (rand() % 43);
        while(c > 57 && c < 65){
            c = '0' + (rand() % 43);
        }
        cards[i][j] = c;
    }
}

printf("%s \n", cards[1]);

The first loop generates a string of 13 characters which are from 0-9 and A-Z. Then I want to generate an array of 5000 strings where each string's first 13 'letters' are that of firstDigits[13]. The problem is that when I try to print one of those strings like above I get as output all of the strings in the array! Why is this happening?

1
  • There are at least a few errors there. I am unsure of what exactly you are trying to do, though. Commented Apr 13, 2017 at 0:25

3 Answers 3

2

C strings must be null terminated. Printf will output chars until it hits a null. After you finish generating your random string add '\0' to the end. Of course you'll have to increase you array size by 1 to accommodate it.

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

Comments

2

The %s format specifier is only for strings. It's not for arrays of characters. How would it know how many characters to print?

You can use %.13s to print 13 characters.

3 Comments

Does that mean that the array of strings is correctly generated and I just had a mistake in printf?
@Peter I can't tell. The output bug is blocking the ability to tell if the generated array is correct. Fix it and keep going.
Do you mean "%.13s"?
0

Since there are 16 characters for each outer index (char [][16]), you can use an array to print each character:

for(j=0;j<16;j++)
    printf("%c", cards[1][j]);

In this case, this prints every character of the outer index 1.

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.