Reputation: 299
Running this gives me a seg fault (gcc filename.c -lm), when i enter 6 (int) as a value. Please help me get my head around this. The intended functionality has not yet been implemented, but I need to know why I'm headed into seg faults already.
Thanks!
#include<stdio.h>
#include<math.h>
int main (void)
{
int l = 5;
int n, i, tmp, index;
char * s[] = {"Sheldon", "Leonard", "Penny", "Raj", "Howard"};
scanf("%d", &n);
//Solve Sigma(Ai*2^(i-1)) = (n - k)/l
if (n/l <= 1)
printf("%s\n", s[n-1]);
else
{
tmp = n;
for (i = 1;;)
{
tmp = tmp - (l * pow(2,i-1));
if (tmp <= 5)
{
// printf("Breaking\n");
break;
}
++i;
}
printf("Last index = %d\n", i); // ***NOTE***
//Value lies in next array, therefore
++i;
index = tmp + pow(2, n-1);
printf("%d\n", index);
}
return 0;
}
Upvotes: 0
Views: 171
Reputation: 6041
You are using pow function, which is not so efficient.
here is my solution in Python.
from math import ceil
names = ['Sheldon', 'Leonard', 'Penny', 'Rajesh', 'Howard']
n = int(raw_input())
i = 0
j = 1
k = len(names)
while i <= n:
i += k
k += k
j += j
print names[int(ceil((n - (i - k * 0.5)) / (j * 0.5)) - 1)]
I hope this helps.
Upvotes: -1
Reputation: 121427
When you input 6 for n
and s[n-1]
, you are doing out of bounds access:
printf("%s\n", s[n-1]);
Because there are only 5 pointers in the array. So only 0-4 are valid indexes.
Upvotes: 2