NugNugs NugNugs - 3 months ago 7
C Question

Contents of variables are unexpectedly changing?

#include <stdio.h>
#include <string.h>

main()
{
int h, m;
char designator[] = "";

printf("Please enter the hours: ");
scanf("%d", &h);
if (h < 0 || h > 23)
{
printf("Please enter a proper time!");
}

else
{
printf("Please enter the minutes: ");
scanf("%d", &m);
if (m > 59 || m < 0)
{
printf("Please enter a proper time!");
}

else if (h == 0 && m == 0)
{
strcpy(designator, "midnight");
}
else if (h == 12 && m == 0)
{
strcpy(designator, "noon");
}
else if (h == 0)
{
strcpy(designator, "am");
h = h + 12;
}
else if (h < 12)
{
strcpy(designator, "am");
}
else if (h > 12)
{
strcpy(designator, "pm");
h = h - 12;
}
printf("The time is: %d:%d %s", h, m, designator);
}
}


Hello there! When I run this code, I get an output that is very unexpected. The variables (m in particular) are not supposed to change. They are taken as input using scanf() but I have no intentions of changing them. I assume the variables have the problem or with the if's but really I have no idea what the problem is with my code :/

This is what appears in the command line:


Please enter the hours: 23

Please enter the minutes: 15

The time is: 11:109 pm


I have tried to identify where the "109" is coming from but I have no clue whatsoever. I'm very new to C so there's probably some things that are not clear to me yet but I'm very willing to learn of them.

Answer

If you do sizeof designator you will see that it has a size of only one byte. Its contents will be the the single character '\0' (the string terminator). That's because of the way you initialize it.

If you create an array without an explicit size, the compiler will deduce the size from whatever data you use to initialize the array with. Since you initialize it with an empty string, an empty string is what it will contain and that's the size it will have.

Because of this you will write out of bounds of the array, and that will lead to undefined behavior.

You need to explicitly set a size of the array, large enough to contain the largest string you will copy into it.

E.g.

char designator[128] = "";