[英]segmentation fault in 2d array
我正在編寫有關 lcs 算法的代碼。 由於這種情況,我使用 malloc 函數為 lcs 算法制作了 2d lcs_table。 在將數組初始化為 0 時,存在分段錯誤。 不知道哪里錯了。。
void findLCS(char lcs_1[], const char s1[], const char s2[])
{
/* FILL */
int i,j,k,l;
int s1_len = strlen(s1);
int s2_len = strlen(s2);
// int LCS_array[s1_len+1][s2_len+1]; //>>malloc use
//printf("%d, %d\n",s1_len, s2_len);
int **LCS_array;
LCS_array = malloc(sizeof(char)*(s1_len+1));
for(i=0;i<=s1_len;i++){
LCS_array[i] = malloc(sizeof(char)*(s2_len+1));
if(LCS_array[i]==NULL){
perror("malloc:");
exit(1);
}
}
printf("s1_len : %d, s2_len : %d\n",s1_len,s2_len);
for (i = 0 ; i <=s1_len;i++){
for (j = 0 ; j <=s2_len;j++){
printf("[%d,%d] ",i,j);
LCS_array[i][j] = 0;
}
printf("\n");
}
for(i = 1 ;i<=s1_len;i++){
for(j = 1;j<=s2_len;j++){
if (s1[i-1]==s2[j-1]){
LCS_array[i][j] =(LCS_array[i-1][j-1]+1);
}
else if(LCS_array[i-1][j]>=LCS_array[i][j-1]){
LCS_array[i][j] =LCS_array[i-1][j];
}
else{
LCS_array[i][j]=LCS_array[i][j-1];
}
}
}
int index = LCS_array[s1_len][s2_len];
lcs_1[index] = '\0';
i = s1_len, j = s2_len;
while (i > 0 && j > 0) {
if (s1[i - 1] == s2[j - 1]) {
lcs_1 [index-1] = s1[i-1];
i--;
j--;
index--;
}
else if (LCS_array[i - 1][j] < LCS_array[i][j - 1])
j--;
else
i--;
}
}
jeon@ubuntu:~/hw5$ ./hw5_cor ccgtttcca tgcccatct
$ ./hw5_cor ccgtttcca tgcccatct
s1_len : 9, s2_len : 9
[0,0] [0,1] [0,2] [0,3] [0,4] [0,5] [0,6] [0,7] [0,8] [0,9]
[1,0] [1,1] [1,2] [1,3] [1,4] [1,5] [1,6] [1,7] [1,8] [1,9]
[2,0] [2,1] [2,2] [2,3] [2,4] [2,5] [2,6] [2,7] [2,8] [2,9]
[3,0] [3,1] [3,2] [3,3] [3,4] [3,5] [3,6] [3,7] [3,8] [3,9]
Segmentation fault (core dumped)
我在哪里更正代碼?
LCS_array = malloc(sizeof(char)*(s1_len+1));
應該是LCS_array = malloc(sizeof(char*)*(s1_len+1));
在 char 關鍵字后加上一個星號。 這是因為LCS_array
是一個指針的指針,換句話說它應該是一個數組,其中每個元素也是一個指向整數數組的指針。
有關在 C 中創建 2D 數組的更多信息,請參閱 Geeksforgeeks 的 這篇文章。我認為這應該可以解決分段錯誤問題(我不確定,因為我在 Windows 上)。
這是 GFG 文章中有關如何在 C 中動態創建 2D 數組的示例:
int r = 3, c = 4, i, j;
int** arr = (int**)malloc(r * sizeof(int*));
for (i = 0; i < r; i++)
arr[i] = (int*)malloc(c * sizeof(int));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.