【发布时间】:2023-03-14 07:42:01
【问题描述】:
我的代码:
#include <stdio.h>
#include <stdint-gcc.h>
#include <string.h>
int checkAnagram(char *word1, char *word2, int length){ //This function compares the two strings by storing the occurrences of their letters in a histogram, and then comparing that histogram.
printf("test4");
int i, n;
int letterCount1[26], letterCount2[26];
char letter;
for(i=0;i<length;i++){
letter = word1[i];
letterCount1[letter-'a']++;
}
for(n=0;n<length;n++){
letter = word2[n];
letterCount2[letter-'a']++;
}
for(i=0;i<26;i++){
for(n=0;n<26;n++){
if(letterCount1[i]==letterCount2[n]){
i++;
} else {
return 0;}
}
}
return 1;
}
void main(){
int length1, length2,i,n;
scanf("%d", &length1);
int lengthArray1[length1]; //Array used to store the length of each string (without white spaces)
char *sentenceArray1[length1];
char tempString[100000];
//The array for storing the first set of sentences, and a temporary string used
//for allocating memory in the next loop
for(i=0;i<=length1;i++){
fgets(tempString, 100000, stdin); //Reads the first line of input (up to and including \0), with a maximum line length which will probably be sufficient.
sentenceArray1[i]=malloc((strlen(tempString))*sizeof(char)); //Allocates just enough memory for each string (including \0).
int index = 0;
for(n=0;n<(strlen(tempString));n++){
if(tempString[n] != ' ' && tempString[n] != '.') { //Copies only from the input if the character is not a whitespace.
sentenceArray1[i][index++]=tolower(tempString[n]);
}
}
sentenceArray1[i][index] = '\0';
lengthArray1[i]=strlen(sentenceArray1[i]);
printf("test1\n");
}
scanf("%d", &length2);//Same stuff as above, now for the second set of strings.
int lengthArray2[length2], index;
char *sentenceArray2[length2];
for(i=0;i<=length2;i++){
fgets(tempString, 100000, stdin);
sentenceArray2[i]=malloc((strlen(tempString))*sizeof(char));
index = 0;
for(n=0;n<(strlen(tempString));n++){
if(tempString[n] != ' ' && tempString[n] != '.') {
sentenceArray2[i][index++]=tolower(tempString[n]);
}
}
sentenceArray2[i][index] = '\0';
lengthArray2[i]=strlen(sentenceArray2[i]);
printf("test2\n");
}
printf("test3");
for(i=0;i<length1;i++){
for(n=0;n<length2;n++){
if(lengthArray2[i]==lengthArray1[i]){
if(checkAnagram(*sentenceArray1[n],*sentenceArray2[i], length1)==1){ //Sends strings only to the checkAnagram function if they are of the same length.
printf("%d ",i);
}
}
}
printf("\n");
}
}
假设的输入和输出:
我一定是在某处弄乱了数组和指针,但是来自控制台的有限反馈加上我对 C 编程的有限经验使得很难找到错误。我的输出一直打印“test4”一次,然后崩溃,标题中给出了异常。
我希望我想要实现的目标很明确,但不幸的是,我无法更准确地说明错误。
【问题讨论】:
-
您需要学习如何使用调试器。这将为您节省无数小时,让您不知道您的程序刚刚发生了什么。
-
刚刚从谷歌快速搜索到异常是 access_violation 所以你可能试图访问一些你无权访问的内存。
-
如果
checkAnagram()接收到非小写字母,它似乎可以,letterCount1[letter-'a']++会产生问题。 -
@SharonJDDorot 它是 C99 中引入的“可变长度数组”
-
@SharonJDDorot 它是标准 C。C99 标准版本。
标签: c arrays exception pointers memory