Why does it print random characters when exceeding 44 characters

I am learning C from the book C-Programming: A Modern Approach. Right now I'm going to do array exercises. One exercise is to write a filter that prints an input message in different ways.

I got it so far (see code below), everything works fine as long as the number of characters is more than 44, then it prints random characters. If the number of characters is less than 44, everything works fine. I totally don’t understand why he does it. Where is the problem and what could be the solution?

int i = 0, k = 0;
char message[k],ch;

printf("Enter a message: ");
while(toupper(ch = getchar()) != '\n')
{
    message[k] = ch;
    k++;
}
printf("In B1FF-speak: ");
for (i = 0; i <= k - 1; i++)
{
    switch(toupper(message[i]))
    {
        case 'A':
            printf("4");
            break;
        case 'B':
            printf("8");
            break;
        case 'E':
            printf("3");
            break;
        case 'I':
            printf("1");
            break;
        case 'O':
            printf("0");
            break;
        case 'S':
            printf("5");
            break;
        default:
            printf("%c", toupper(message[i]));
            break;
    }
}
+4
source share
1 answer
int i = 0, k = 0;
char message[k],ch;

message (VLA). ( , 1990 C, ​​ 1999 ​​ 2011 .)

k 0, message 0. C . ( , ). undefined.

VLA , . k . , , , .

44. undefined. , , - , , ""; , , .

, , ( , ), realloc() . (realloc() , . , , , , , .)

+9

Source: https://habr.com/ru/post/1569082/


All Articles