Q: Format Specifier Q and unique bug in Mario Solution to Pyramid algorithm Okay I have two problems with my solution to this problem, I was hoping I could get some help on. The problem itself is being able to print out #s in a specific format based on user input.
My questions are: 


*

*When I input 7, it outputs the correct solution, but when I output 8 (or higher), my buffer, for whatever reason add some garbage at the end, which I am unsure why it happens. I would add a picture but I don't have enough rep points for it :(

*In my code, where I've inputted **HELPHERE**, I'm unsure why this gives me the correct solution. I'm confused because in the links I've read (on format specifiers) I thought that the 1 input (x in my case) specified how many spaces you wanted. I thought this would've made the solution x-n, as each consequent row, you'd need the space segment to decrease by 1 each time. Am I to understand that the array somehow reverses it's input into the printf statement? I'm confused because does that mean since the array increases by 1, on each subsequent iteration of the loop, it eats into the space area?
int main(void){

    printf("Height: ");
    int x = GetInt();
    int n = 1;
    int k=0;
    char buff[x];           /* creates buffer where hashes will go*/

    while(n<=x){            /* stops when getint value is hit*/
        while(k<n)              /* fill buffer on each iteration of loop with 1 more     hashtag*/
        {
            buff[k] = '#';
            k++;
        }

        printf("%*s",x, buff);  /*makes x number of spaces ****HELPHERE*****, then prints buffer*/
        printf("  ");
        printf("%s\n",buff);    /*prints other side of triangle */

        /*printf("%*c \n",x-n, '\0');*/

        n++;
    }

}


A: *

*Allocate enough memory and make sure the string is null terminated:
char buff[x+1];//need +1 for End of the string('\0')
memset(buff, '\0', sizeof(buff));//Must be initialized by zero


*Print as many blanks as requested by blank-padding an empty string:
printf("%*s", x, "");

※the second item was written by  Jonathan Leffler.

A: In printf("%*s",x, buff);, buff in not null character terminated.
Present code "worked" sometimes as buff was not properly terminated and the result was UB - undefined behavior.  What likely happened in OP's case was that the buffer up to size 7, fortunately had '\0' in subsequent bytes, but not so when size was 8.
1) As per @BLUEPIXY, allocated a large enough buffer to accommodate the '#' and the terminating '\0' with char buff[x+1];
2) Change while loop to append the needed '\0'.
while (k<n) {
  buff[k] = '#';
  k++;
  }
buff[k] = '\0';

3) Minor:insure x is valid.
 if (x < 0) Handle_Error();
 char buff[x]; 

4) Minor: Return a value for int main() such as return 0;.
