[英]How to resolve: Caught unexpected signal: SIGSEGV (11). Invalid memory access
A kyu on codewars asks for the following: codewars 上的 kyu 要求以下内容:
Complete the method which accepts an array of integers, and returns one of the following:完成接受整数数组的方法,并返回以下内容之一:
"yes, ascending" - if the numbers in the array are sorted in an ascending order "yes, descending" - if the numbers in the array are sorted in a descending order "no" - otherwise You can assume the array will always be valid, and there will always be one correct answer. “是,升序” - 如果数组中的数字按升序排序 “是,降序” - 如果数组中的数字按降序排序 “否” - 否则您可以假设数组将始终有效,并且总会有一个正确的答案。
I put together the following but run into "Caught unexpected signal: SIGSEGV (11). Invalid memory access" when testing.我将以下内容放在一起,但在测试时遇到了“捕获意外信号:SIGSEGV (11)。无效的 memory 访问”。 Can someone please explain the error to me and what part of the script triggers it?有人可以向我解释错误以及脚本的哪一部分触发它吗?
#include <stdio.h>
char* isSortedAndHow(int* array, int arrayLength)
{
// Create an empty array where ascending or descending test results will be stored
int results[] = {};
int i;
// If the value is greater than the previous one add a 1, if smaller add a 0, if equal, add 1000
for (i = 1; array[i]; i++){
if (array[i] < array[i-1]){
results[i-1] = 0;
} else if (array[i] > array[i-1]) {
results[i-1] = 1;
} else {
results[i-1] = 1000;
}
}
// Add the value of all values in the results array and return the answer
int sum = 0;
for (i=0; results[i]; i++) {
sum = sum + results[i];
} if (sum == 0) {
return "yes, descending";
} else if (sum == (arrayLength - 1)) {
return "yes, ascending";
} else {
return "no";
}
}
The culprit is the line罪魁祸首是线路
int results[] = {};
You declare an array of int
with a size of zero.您声明一个大小为零的int
数组。 Further down the code you try to write into that array: BOOM!进一步向下尝试写入该数组的代码:BOOM!
One possible solution is to allocate the array with the size arrayLength
.一种可能的解决方案是分配大小arrayLength
的数组。 But as commenters said, you don't need this array at all.但正如评论者所说,你根本不需要这个数组。 Rethink your algorithm.重新考虑你的算法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.