Home > Software design >  What make # go in different line instead of continuing the line?
What make # go in different line instead of continuing the line?

Time:12-01

I'm not sure why # go in the wrong line when it supposed to continue after 'u'

#include <stdio.h>
#define LEN 5

int inputNumber() {
    int size;
    printf("Input Size: ");
    scanf("%d",&size);
    printf("===\nTriangle Size is %d\n===\n",size);
    return size;
}

void printTriangle(int size, char ch[]) {
    for(int i = 0; i < size; i  )
    {
        for(int j = 0; j <= i; j  )
        {
            if(j<=LEN)
                printf("%c ",ch[j]);
            if(j>LEN)
                printf("# ");
        }
        printf("\n");
    }
}

int main() {
    char arr_char[LEN] = {'a','e','i','o','u'};
    int number;
    number = inputNumber();
    printTriangle(number,arr_char);
    return 0;
}

I used to ask about this same code before but I want to try using if-else instead of ? : because I haven't learn that yet in class so I want to know if it's possible using basic thing like if-else.

enter image description here

CodePudding user response:

Your code has undefined behavior because you are trying to access memory beyond the declared array arr_char in this if statement

        if(j<=LEN)
            printf("%c ",ch[j]);

The valid range of indices for the array is [0, LEN ).

You need to rewrite the if statement like

        if(j < LEN)
            printf("%c ",ch[j]);

As it is seen from the output picture it seems that in the byte just after the array it occurred such a way that there is stored the new line character '\n'.

a e i o u
a e i o u

a e i o u
 #
  • Related