简体   繁体   English

测试案例中的细分错误

[英]Segmentation fault in test cases

So, the question is as follows: Given any array(reasonably large) of integers, return the maximum difference between any two elements in the array such that the larger element occurs at a higher index than the smaller element. 因此,问题如下:给定任意整数数组(合理地大),返回数组中任意两个元素之间的最大差,以使较大的元素比较小的元素出现在更高的索引处。 Return -1, if no such pair is found. 如果找不到这样的对,则返回-1。 Example: 例:

7 2 3 10 2 4 8 1 7 2 3 10 2 4 8 1

where the first element is the size of the array(or the number of lines being entered), and the rest are the elements. 其中第一个元素是数组的大小(或输入的行数),其余元素是元素。 Sample output is 8(10-2) for the above. 上面的示例输出为8(10-2)。

My code is as follows: 我的代码如下:

int A[20],size;

scanf("%d",&size);
for(int i=0;i<size;i++){
scanf("%d\n",&A[i]);
}
int diff = A[1]-A[0];
int currsum = diff;
int maxsum = currsum;

for(int i=1; i<size-1; i++)
{
    // Calculate current difference for the loop
    diff = A[i+1]-A[i];

    // Calculate current sum for the loop
    if (currsum > 0)
       currsum += diff;
    else
       currsum = diff;

    // Update max sum(if needed)
    if (currsum > maxsum)
       maxsum = currsum;
}

printf("%d",maxsum);

This is a question from Hackerrank, but it runs for only three out of 10 possible testcases. 这是Hackerrank的一个问题,但是在10个可能的测试用例中,只有3个可以运行。 The rest of the cases return a segmentation fault. 其余案例返回分段错误。 Any idea would be helpful. 任何想法都会有所帮助。

As mentioned in the comments, you've declared A to hold just 20 integers. 如评论中所述,您已经声明A仅容纳20个整数。 But the question can send up to 1,000,000 integers. 但是问题最多可以发送1,000,000个整数。 That's the mistake! 那是错误!

Using pointers make this more important. 使用指针使其变得更加重要。 First declare A as pointer of integers, then, read the first element of the array, using this integer you can allocate memory dynamically ( malloc() or calloc() function) for your array A . 首先A声明为整数指针,然后读取数组的第一个元素,使用该整数可以为数组A动态分配内存( malloc()calloc()函数)。 so the size of A will dynamic and you can resize it in function of the first element. 因此A的大小会动态变化,您可以根据第一个元素的功能对其进行调整。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM