When you use
memset(stair, ' ', n *(sizeof(char)));
the white space character ' '
is not equal to a null character '\0'
(which you might think it is). This means in turn that the array elements of stair
aren't set to 0
(which would determine a strings end).
They are just all initialized to contain white space but there is actually no indicator at all inside of the array, that determines where a string ends, when the array is addressed by string operating functions.
Such an operation encounters a specific amount of '#'
hashtags first and thereafter only white space character/s, but no null character.
Printing a string with
printf("%s\n", stair);
is then undefined behavior, because there is no delimiter to determine the string's end.
Use
memset(stair, '\0', sizeof(char) * n);
or
memset(stair, 0, sizeof(char) * n);
instead.
As side note here, allocating an array might not be most efficient way to go. Better use an algorithm which uses a single character constant for '#'
and prints increase the amount of it shown in the output per iteration.
To answer your concerns:
It works fine if n = 8 or lower, but if n = 9 or higher it still prints the staircase, but with some garbage symbol at the end of every line. I just don't quite understand why this works for some numbers and not for others.
It has nothing at all to do with the value of n
. Undefined behavior does not need to provide wrong results. In fact, all of your executions were subject to undefined behavior regardless whether it showed the expected output or not.
Also variable length arrays (VLAs), like stair
is, are not supported by every implementation and only mandatory to C99 conforming implementations. They are only made available by non-standard compiler extensions when compliant to other standards. May use malloc()
instead to make your program more portable.