-3

Why do i get runtime eror when running this code in gcc compiler?? It works fine in turboC. I have been working on this for couple of days with no progress at all. Kindly help.

#include<stdio.h>

int main()
{
int T,i=0,num,sum,temp,j;
int *N;
scanf("%d",&T);
while(i++<T)
{
scanf("%d",N);
temp=*N;
while((*N)-->0)
{

    sum=0;
    num=(*N)+1;
    for(j=0;j<64;j++)
    {
    if(num&1)
        sum+=1;
    num=num>>1;
    }
if(((*N)+1+sum)==temp)
    break;
}
printf("%d\n",((*N)<0)?-1:(*N)+1);

}

return 0;

}

1 Answers1

2

include the header file

# include <stdlib.h>

Allocate memory to the pointer before using it.

int *N;
N = (int *)malloc (sizeof (int));

Free the allocated memory after using it

free (N);
Adarsh
  • 883
  • 7
  • 18
  • 2
    Better to not use a pointer at all. I don't see any reason it is necessary in this code. – Retired Ninja Sep 03 '14 at 04:03
  • 1
    Since he is using it maybe its required for him, let him use but in a correct way. – Adarsh Sep 03 '14 at 04:05
  • i used pointers to reduce time of execution below 1 second. i couldnt do it with int. – Manu Mathew Sep 03 '14 at 04:08
  • Ok it's fine @Manu Mathew, just allocate memory it should work. – Adarsh Sep 03 '14 at 04:09
  • @ManuMathew That makes no sense at all unless this is not the actual code you're using. – Retired Ninja Sep 03 '14 at 04:11
  • Actually @Manu Mathew dynamic memory allocation will take more time than statically allocating memory. In this case if you don't use pointer it would be faster. – Adarsh Sep 03 '14 at 04:11
  • it was a problem in hackerearth. the time reduced from 1.0015s to .1342 s after using pointer. I am just a beginner. so i dont know why. Thank you for the reply.:) I will try this. – Manu Mathew Sep 03 '14 at 04:14
  • 1
    @ManuMathew using pointer won't save you time but cost you more for allocating on heap and pointer dereference. Use automatic variables on stack instead, just `int N` is enough – phuclv Sep 03 '14 at 04:33
  • 1
    @Adarsh if you use pointer, remember to delete if after using, and [don't cast the result of malloc in C](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – phuclv Sep 03 '14 at 04:33
  • Thank you all. I got the pointer part working correctly. As you all said the time remained kind of the same only. So the problem is still unsolved but learned a lot from this. Thank you – Manu Mathew Sep 03 '14 at 18:07