سؤال

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? :)

هل كانت مفيدة؟

المحلول

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'.

نصائح أخرى

use

ast[0]=0;

will fix it - aka initialize it

alternative using snprintf:

 #include <stdio.h>
 #include <string.h>
 #define MAX 32
 int main(void)
 {
     unsigned int cur, max;
     char ast[32];
     printf("Enter the triangle's size: ");
     scanf("%d", &max);
     if (max > MAX)
    return -1;
     for(cur = 1; cur <= max; cur++)
     {
     if(cur == 1)
         {
          snprintf(ast,2,"*");
              printf("\n");
         }
     else 
          strlcat(ast, "*",cur + 1);
     printf("%s\n", ast);
    }
    return 0;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top