int *rrange(int start, int end);
有人要求我编写一个函数并使用 malloc 分配一个整数数组,并用连续的值填充它
从 end 开始到 start 结束的值(包括 start 和 end!),然后
返回指向数组第一个值的指针。这些函数适用于小数字,当用大数字进行测试时,我得到seg failure
。我认为由于达到了 int
的限制,我遇到了 seg failure
。我该如何解决这个问题?
/*- With (1, 3) you will return an array containing 3, 2 and 1
- With (-1, 2) you will return an array containing 2, 1, 0 and -1.
- With (0, 0) you will return an array containing 0.
- With (0, -3) you will return an array containing -3, -2, -1 and 0.*/
#include <stdlib.h>
int *rrange(int start, int end)
{
int *range;
int i;
i = 0;
range = (int *)malloc(sizeof(int *));
if (end <= start)
{
while (end <= start)
range[i++] = end++;
}
else
{
while (end >= start)
range[i++] = end--;
}
return (range);
}
= Test 1 ===================================================
$> ./pw53y11cbachacu14eue5cab
$> diff -U 3 user_output_test1 test1.output | cat -e
Diff OK :D
= Test 2 ===================================================
$> ./o1jrm4t3vqengizvj1tlwab4 "21" "2313" "12"
$> diff -U 3 user_output_test2 test2.output | cat -e
Diff OK :D
= Test 3 ===================================================
$> ./usl3i1tc1xv9tr1gs9n5x5vr "2147483647" "2147483640" "7"
$> diff -U 3 user_output_test3 test3.output | cat -e
--- user_output_test3 2016-06-08 16:26:16.000000000 +0200$
+++ test3.output 2016-06-08 16:26:16.000000000 +0200$
@@ -1,8 +1,8 @@$
-0$
-0$
-0$
-0$
-0$
-0$
-0$
+2147483640$
+2147483641$
+2147483642$
+2147483643$
+2147483644$
+2147483645$
+2147483646$
$
Diff KO :(
Grade: 0
= Final grade: 0 ===============================================================
最佳答案
您的问题来自于malloc
:
而不是
range = (int *)malloc(sizeof(int *));
你应该写:
range = malloc(nb_of_integer_in_range * sizeof (int));
由您来计算nb_of_integer_in_range
,例如:
int nb_of_integer_in_range;
if (end > start)
{
nb_of_integer_in_range = end - start + 1;
}
else ...
关于c - C中大数字的int指针函数seg错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37718134/