[英]C program - Seg fault, cause of
Running this gives me a seg fault (gcc filename.c -lm), when i enter 6 (int) as a value. 当我输入6(int)作为值时,运行此命令会给我一个段错误(gcc filename.c -lm)。 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;
}
When you input 6 for n
and s[n-1]
, you are doing out of bounds access: 当为n
和s[n-1]
输入6时,您正在执行越界访问:
printf("%s\n", s[n-1]);
Because there are only 5 pointers in the array. 因为数组中只有5个指针。 So only 0-4 are valid indexes. 因此只有0-4是有效索引。
You are using pow function, which is not so efficient. 您使用的是pow功能,效率不高。
here is my solution in Python. 这是我在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. 我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.