I want to give the program an integer value from 1 to 26 (doesn't need to be hardcoded) that creates a char Array that is filled with the letters from A to letter n. This is the code:
int main(int argc, char *argv[])
{
int n = atoi(argv[1]);
char comb[n];
for (int i = 0; i < n; i )
comb[i] = 65 i;
printf("%s", comb);
}
The problem is, that if i hand over values from 8 - 15 and 24 - 26, the output shows something like this: ABCDEFGH�������
However, if i hardcode n to be one of the problematic values from above, the output is just right.
Can somebody explain to me, why the program puts out the extra �. Thanks
CodePudding user response:
The standard way to convert a string to a numeric type in C is to use the
strto*
family of functions. In your case, you would want something like:int count = strtol(argv[1], // String NULL, // Optional output pointer to where the scan stopped 10) // Radix
I'd also check that
argc > 2
, i.e. thatargv[1]
was actually passed by the user.%s
expects a pointer to a null terminated string. In other words,printf
has no way of knowing where the string argument stops until it sees the'\0'
, so what you're seeing is some other part of your process memory being printed out as text. To fix: allocaten 1
forcomb
, andmemset(comb, n 1, 0);
before the loop, or setcomb[n] = '\0'
right after the loop.