gpt4 book ai didi

c - 段错误(核心转储)错误,在 C 搜索函数中

转载 作者:太空宇宙 更新时间:2023-11-04 06:26:03 24 4
gpt4 key购买 nike

我正在尝试编写一个 C 程序来获取离散正整数数组并找到最长递增子序列的长度。

'int* a'是随机生成的整数数组,长度为'int b'

调用:lis_n = answer(seq, seq_size);

功能:

int answer(int* a, int b) {
if (a == NULL) {return -1;}
int i = 0;
int j = 0;
int k = 0;
//instantiate max and set it to 0
int max = 0;
//make an array storing all included numbers
int included[b];
memset(included, 0, b*sizeof(int));
//create a pointer to the index in included[] with the largest value
int indexMax = 0;
//create a pointer to the index in a[]
int indexArray = 0;
//index of a[] for max included
int maxToA = 0;
//set the first included number to the first element in a[]
included[indexMax] = a[indexArray];
//loop until break
while (1) {
if (a[indexArray] > included[indexMax]/*digit greater than last included*/) {
//include the digit
included[indexMax+1] = a[indexArray];
//increment current max pointer
indexMax++;
}
j = b - 1;
while (indexArray >= j/*pointer is at end"*/) {
if (j == (b - 1)) {
if ((indexMax+1) > max/*total is greater than current max*/) {
max = indexMax + 1;
}
}
if (a[b-1] == included[0]/*last element is in included[0], stop*/) {
return max;
} else {
//max included is set to zero
included[indexMax] = 0;
//max included pointer decreased
indexMax--;
//set array pointer to new max included
for (k=0;k<(b-1);k++) {
if (a[k] == included[indexMax]) {
indexArray = k;
}
}
//increment array pointer
indexArray++;
j--;
}
}
indexArray++;

printf("(");
for (i=0;i<b;i++) {
printf("%d,",included[i]);
}
printf(")");
}
}

我在运行时在终端中收到“段错误(核心已转储)”。

任何帮助都会很棒。

最佳答案

你已经声明了

int indexMax = 0;

这里你用它作为数组索引

incuded[indexMax] = 0;

递增和递减

indexMax++;
...
indexMax--;

你检查它的范围但你不限制它,你改变你与之比较的值

if ((indexMax+1) > max/*total is greater than current max*/) {
max = indexMax + 1;
}

你永远不会检查 indexMaxb0

int included[b];

所以你几乎可以肯定会超出 included[] 的范围。

一些一般性的建议。让你的函数和变量名有意义。尽可能避免过早退出函数。尽可能避免 while(1)。并且从不对数组大小(包括 C“字符串”)做出假设。投入管理费用似乎很辛苦,但这是有返回的。返回不仅仅是捕获意外错误,它让您在编写代码时思考您正在编写的代码。

关于c - 段错误(核心转储)错误,在 C 搜索函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26783760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com