The reason of your confusion is that you do not understand variable length arrays correctly.
For starters take into account that you may not declare a variable length array with the size equal to 0
. So in any case this array declaration
int i = 0,j = 0;
char msg[i];
is incorrect.
To change the size of the array msg
it is not enough to change the value of the variable i
used in the array declaration. It is required that the execution control of the program would go through the array declaration each time for a new value of i
.
Here is a demonstrative program.
#include <stdio.h>
int main(void)
{
int i = 1;
L1:;
char msg[i];
printf( "The size of msg is %zu\n", sizeof( msg ) );
if ( i++ < 10 ) goto L1;
}
The program output is
The size of msg is 1
The size of msg is 2
The size of msg is 3
The size of msg is 4
The size of msg is 5
The size of msg is 6
The size of msg is 7
The size of msg is 8
The size of msg is 9
The size of msg is 10
As you can see, the control is transferred to the label L1
after changing the variable i
. And the control goes through the declaration of the array with a value of the variable i
.
But the early stored values in the array will be lost.
According to the C Standard (6.2.4 Storage durations of objects)
7 For such an object that does have a variable length array type, its
lifetime extends from the declaration of the object until execution of
the program leaves the scope of the declaration.35) If the scope is
entered recursively, a new instance of the object is created each
time. The initial value of the object is indeterminate.
So either use a character array with a fixed size or reallocate the array dynamically within the loop using the standard function realloc
.
Here is a demonstrative program.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *msg = malloc( sizeof( char ) );
size_t i = 0;
printf( "Please enter a msg you want to translate: " );
for ( char c; scanf( "%c", &c ) == 1 && c != '\n'; i++ )
{
char *tmp = realloc( msg, i + 1 );
if ( tmp == NULL ) break;
msg = tmp;
msg[i] = c;
}
msg[i] = '\0';
printf( "You entered %zu characters: %s\n", i, msg );
free( msg );
return 0;
}
Its output might look like
Please enter a msg you want to translate: Humza Ahmed
You entered 11 characters: Humza Ahmed