I'm learning C from a book C programming:Modern approach. Right now I'm going trough exercises about arrays. One of the exercises is to write a filter that prints the input message differently.
I've gotten so far (see the code below), everything works fine, until the character count exceeds 44, then it prints random symbols. If the character count is below 44 everything works fine. I have absolutely no clue why it does that. Where is the problem and what might 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;
}
}
int i = 0, k = 0;
char message[k],ch;
You've defined message
as a variable length array (VLA). (This is a feature that doesn't exist in the 1990 version of C; it was added by the 1999 standard and made optional by the 2011 standard.)
Since the value of k
is 0
, the length of message
is 0
. C does not support zero-length arrays. Defining an array with a constant length of zero is illegal (a constraint violation, requiring a diagnostic). Defining a variable length array with a length of zero has undefined behavior.
The length of a VLA is fixed when it's defined. Changing the value of k
later on does not change the length of the array. Your code seems to assume that it will.
Your program seems to work for lengths up to 44. That's the nature of undefined behavior. The worst thing that can happen is that your program seems to work "correctly"; that just means that you have a bug that's difficult to detect.
If you want to store arbitrarily many elements in an array, you can either define it with a size that's big enough in the first place (it can be difficult or impossible to determine how big it has to be), or you can use realloc()
to allocate the array dynamically and expand it as needed. (realloc()
doesn't actually expand the array; it creates a new array with a larger size and copies the contents of the old array into the new array. And it can fail if there isn't enough available memory; always check the value it returns to determine whether it succeeded or failed.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With