Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input large strings in C

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.

like image 763
akashrajkn Avatar asked Feb 17 '26 12:02

akashrajkn


1 Answers

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 );
   ....
 }
like image 59
Alfred Huang Avatar answered Feb 19 '26 02:02

Alfred Huang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!