Home > database >  How to initialize the size of an array
How to initialize the size of an array

Time:12-15

int main()
{
    char s1[]={0};
    char s2[]={0};
    scanf("%s",s1);
    scanf("%s",s2);
    printf("%s",s2);
}

My question: When type some letter into S1 and S2 ,S2 will copy my S1. Why is this problem and can you initialize an array without identifying its size.

CodePudding user response:

The [] means that the compiler will pick the size after the amount of items provided in the initializer list. In this case you have one item 0 so the arrays get size one. You cannot change the size afterwards. Therefore your code has undefined behavior bugs - you allocated too little memory and the scanf calls will write out-of-bounds of the arrays.

In case you need to change an array size in run-time, you need to either use dynamic memory allocation with malloc or use a variable-length array (VLA).

CodePudding user response:

You can get the size of an array at run time too by declaring it in a variable and then getting it as a input using scanf.

But in your program you have already declared the array so the size of array is also fixed as 1.

  •  Tags:  
  • c
  • Related