0

I have a question about these two different mini-programs:

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int main(void)
{
    char three[3];
    three[0] = 65;
    three[1] = 65+3;
    three[2] = 65;
    printf("%s is the key\n", three);
}
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, string argv[])
{
    char three[3];
    three[0] = 65;
    three[1] = 65+3;
    three[2] = 65;
    printf("%s is the key\n", three);
}

Why is it that when I compile the first one, "ADA" is returned, but for the second one, if I pass in any input (which to my understanding shouldn't affect what's printed), "ADA" plus a random string of more characters is returned?

Thanks!

0

The issue is that in the first case, you are just lucky.

If you want to print a char array as a 'string' (using the %s format specifier), then you want to be sure that your char array is null-terminated. (The Null char is what signifies the end of a string).

You have declared char three[3]; and set the 3 chars to values. None of those values is a null, so it is not a string and cannot be successfully printed as such.

The only reason it worked in your first program is because the variable happened to be stored in memory where the byte directly after those 3 chars happened to be 0x00 (ie, null).

Always be sure to null-terminate any char array you are planning to use with a string function/format.

char three[4]; in this case with three[3] == '\0'; (or == 0;)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .