I wrote a code with the following specified constraints:
Hence I chose the data types for my variables accordingly. However my code fails all the test cases saying segmentation fault. (possibly because the array size they input is very large.) Is there a way to get more stack space or heap space? or get around this problem by declaring the array in some other way? Is there something else that's causing segmentation fault? Other people have solved this problem, so there must be a way.
this is the code:
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
long find_index(long x, long *cost, long n, long used_index)
{
long i;
for(i = 0; i < n; i++)
if(*(cost + i) == x && i != used_index)
return (i+1);
return 0;
}
int purchase(long *cost, long n, long money)
{
long i, index;
for(i = 0; i < n ;i++)
{
index = find_index((money - *(cost - i)),cost,n,i);
if(index)
{
printf("%ld %ld\n",i+1,index);
break;
}
}
free(cost);
return 0;
}
int main(void)
{
int t;
long *cost, money, n, i;
scanf("%d",&t);
while(t > 0)
{
scanf("%ld",&money);
scanf("%ld",&n);
cost = (long *)malloc(n*sizeof(long));
for(i = 0; i < n; i++)
scanf("%ld",(cost+i));
purchase(cost,n,money);
t--;
}
return 0;
}
this is one of the hidden test cases they check for:
35 // this is t
299701136 // this is money
2044 // this is n
50293811 136626876 58515785 59281065 ..... goes on forever...

cost[-i]over pointer juggling:*(cost - i), mostly because it is easier to read.*(cost - i)looks like it's out of bounds.