Search code examples
ctextstrcmp

Annoying strcat() output


I'm having some unknown problem with using strings. It only happens at the instance of this kind of algorithm:

Source.c

#include <stdio.h>
#include <string.h>
main()
{
    int cur, max;
    char ast[32];
    printf("Enter the triangle's size: ");
    scanf("%d", &max);
    for(cur = 1; cur <= max; cur++)
    {
        strcat(ast, "*");
        if(cur == 1)
        {
            printf("\n");
        }
        printf("%s\n", ast);
    }
    getch();
}

This happens:


Overview: A program that creates a triangle out of asterisks (*) of an inputted size.


Enter the triangle's size: 5

■   Z☼]vYⁿbv░↓@*

■   Z☼]vYⁿbv░↓@**

■   Z☼]vYⁿbv░↓@*

■   Z☼]vYⁿbv░↓@**

■   Z☼]vYⁿbv░↓@*


It's supposed to look like this:

Enter triangle size: 5

*

**

***

****

*****

I don't know why. Can someone please help? :)


Solution

  • Your string ast is not initialized, so it will contain garbage, to which you append stuff.

    Init it first - you need a zero terminated string, set the first character to '\0'.