Plz refer to a part of my program given below in //case-1 for declaring dynamic array. When I move “int x[j];” from just below scanf to just after declaring int i; as shown in //Case-2 then the program run but shows nothing any output. kindly tell me why it happens?
//Case-1
#include<stdio.h>
int main()
{
int i,j;
printf(“Enter the size of array=”);
scanf("%d",&j);
int x[j];
printf("%d",x[0]);
return 0;
}
//Case-2
#include<stdio.h>
int main()
{
int i,j;
int x[j];
printf(“Enter the size of array=”);
scanf("%d",&j);
printf("%d",x[0]);
return 0;
}
when program runs, compiler reserves space for the array. in case one it reserves the space of sizeof int * j
while in 2nd case it does the same but this time j can be any value .
The code which you have shared will produce undefined-behaviour or an Error and first share the whole code then only we can tell what is the problem.
[quote=“mkmitra, post:1, topic:61512”]
to complete my given code in Case-1 & case-2 simply you write at last printf("%d",x[0]); for this i already edited my previous question. plz see it.
In C you can not declare an array with variable size but in C++ it is allowed.
In case 1 you have taken input of j and then declared the array with size j.Compiler allocates memory for array of size j and since you haven’t initialized, it prints garbage value.
In case 2 j has initially garbage value. Compiler is unable to allocate memory for the array hence it gives runtime error and program doesn’t execute furhter.