For a particular problem, I have to take string input from the user which can be of size between 1 and 10^5
.
I used the following code
char *a;
a = malloc(100000*sizeof(char));
and inside a loop ( t refers to number of test cases )
while( t-- )
{
scanf( "%d", &n );
scanf( "%s", a );
.....
}
n is the length of the string that is input by the user at run time. The problem is this is giving me "Time Limit Exceeded"
I made few changes to the above code,
while( t-- )
{
scanf( "%d", &n );
char a[n];
scanf( "%s", a );
....
}
This works perfectly fine without "TLE" . But I don't understand why. The reason for using the first code was that time would be saved since allocation of memory is done only once. Am I wrong? Please explain.
If you use malloc, the memory space will create on HEAP
.
While in the second implementation, the memory locates on STACK
.
As I know, stack is faster than heap.
Ref: What and where are the stack and heap?
More over, I think declaring the char
array outside the loop is more reasonable:
char a[100000] = {};
while( t-- )
{
scanf( "%d", &n );
scanf( "%s", a );
....
}