我正在嘗試編寫一個C程序來獲取離散正整數的數組,並查找最長增長子序列的長度。C搜索功能中的分段錯誤(核心轉儲)錯誤
'詮釋* a' 是隨機產生的整數數組,這是長度的 '詮釋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(")");
}
}
我收到運行時在終端中出現「分段故障(核心轉儲)」。
任何幫助都會很棒。
您是否嘗試過使用'gdb'來查看發生錯誤的位置? – 2014-11-06 16:01:20
我還沒有讀過你的程序,但只是看了一眼,我可以看到它使用了很多的數組。嘗試讀取數組的邊界之外可能會發生段錯誤(有時這是經典的「由一個」錯誤)。我會檢查一下,以確保你的程序沒有試圖在某個地方超出數組的最大長度。另外,看看調試。谷歌「用gdb調試seg故障」。 – nanny 2014-11-06 16:03:32
使用gbp和b = 4運行時 – Tom 2014-11-06 16:06:28