【发布时间】:2016-03-14 02:22:58
【问题描述】:
所以基本上当我使用 GCC 编译器编译我的代码时,我没有收到任何错误或警告,但是当我输入第一条数据时,它会显示:
Bus error: 10.
我不确定我做错了什么。我认为问题来自void anagramGrouping(最后一个函数)。我还包含了其余代码以帮助遵循逻辑。
#include <stdio.h>
#include <string.h>
#define Row 2
#define col 20
int wordCount = 0;
int groupCount = 0;
char wordList[Row][col];
char group[Row][col];
// this is where prototypes go
void sortword(char word[col]);
void anagramGrouping(char word[col], char copy[col]);
void resetGroup();
int main() {
int i; // used in for loop to 'get' the strings
char word[col];
resetGroup();
for (i = 0; i < Row; i++) {
scanf("%s", word);
sortword(word);
wordCount++;
}
}
void resetGroup() {
int i;
for (i = 0; i < Row; i++)
strcpy(group[i], " ");
}
void sortword(char word[col]) {
int i = 0;
char temp;
char copy[col]; // used to store a copy of the original word
strcpy(copy, word);
while (word[i] != '\0') {
int j = i + 1;
while (word[j] != '\0') {
if (word[j] < word[i]) {
temp = word[i];
word[i] = word[j];
word[j] = temp;
}
j++;
}
i++;
}
anagramGrouping(word,copy);
}
void anagramGrouping(char word[col], char copy[col]) {
int n;
if (wordCount == 0) {
strcpy(group[0], copy);
}
for (n = 0; n <= groupCount; n++) {
if (strcmp(group[n], word) == 0) {
strcpy(group[n], copy);
} else {
groupCount++;
strcpy(group[groupCount], copy);
}
}
}
【问题讨论】:
-
在 valgrind 或 gdb 中运行你的程序,看看哪一行触发了崩溃。
-
很抱歉不能提供更多帮助,但请尝试检查您的指针/取消引用。
-
您的代码呈现得很糟糕。修复缩进,去掉无用的
// end of functioncmets。 -
我清理了代码的缩进。另外,我以前从未听说过 valgrind 或 gdb。
-
您的
anagramGrouping函数似乎是问题所在。每次发现不匹配时,您都会增加groupCount。在本例中,不允许超过 2(甚至达到),但几乎可以肯定会超过 2,这会导致内存错误。