Printf is not working properly after a new line character

69 views Asked by At

I was trying to make an AYAYA pyramid program in C just because I noticed that the 'A' and 'Y' fits really well togheter and the 'A' can also be the top of the pyramid. The program works, but then I wanted to create a small introduction to the program before the pyramid, but by placing '\n' in the printf it makes the next %s in the printf print something strange, if i print each character one by one it doesn't do this, this is the code for better explanation.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {

        int base;

        if (argc != 2 || (base = atoi(argv[1])) % 2 == 0) {
                printf("Usage: %s n_odd_base\n", argv[0]);
                return 1;
        }

        printf("this \\n infects next string output -->\n");

        int i, j;
        char spaces[base/2];
        
        for (i = 0; i < base/2; i++) {
                spaces[i] = ' ';
        }
        
        for (j = 0; j < base; j += 2) {
                printf("%s", spaces);
                for (i = 0; i <= j; ++i)
                        if (i % 2 == 0)
                                putchar('A');
                        else    
                                putchar('Y');
                printf("\n");
                spaces[base/2-1-j/2] = '\0';
        }

        return 0;
}

this a type of output, if you try it you notice that the random characters change every time.

fuffi@astro ayayatower]$ ./AYAYA.out 5
this \n infects next string output -->
  5õLVA
 AYA
AYAYA

Also if you have any tips to make this program better tell me please, I have very little knowledge with programming and C.

[EDIT]: that problem happens even if there is no introduction and you input 17 or 19, probably others but I know these, if you input 131 it works normally so I don't know.

1

There are 1 answers

0
Vlad from Moscow On

The array spaces does not contain a string

    char spaces[base/2];
    
    for (i = 0; i < base/2; i++) {
            spaces[i] = ' ';
    }
    

So this call of printf

    for (j = 0; j < base; j += 2) {
            printf("%s", spaces);

invokes undefined behavior.

You could declare the array like

    char spaces[base/2 + 1];

    for (i = 0; i < base/2; i++) {
            spaces[i] = ' ';
    }
    spaces[i] = '\0';

Also if base is an odd number then the expression

spaces[base/2-1-j/2] = '\0';

can write outside the array when j = base - 1.