我在C中創建了一個字母頻率計數器,用於跟蹤給定字符串中字符的使用次數。二維數組跟蹤數據,而該程序循環遍歷每個字符:擴大二維數組值的崩潰程序
char* input = "The cat jumped over the fence";
int inputlength = (int) strlen(input);
//keeps track of how many times each character is used
int letterfrequencies[26][2] = {
{'a',0},
{'b',0},
{'c',0},
{'d',0},
{'e',0},
{'f',0},
{'g',0},
{'h',0},
{'i',0},
{'j',0},
{'k',0},
{'l',0},
{'m',0},
{'n',0},
{'o',0},
{'p',0},
{'q',0},
{'r',0},
{'s',0},
{'t',0},
{'u',0},
{'v',0},
{'w',0},
{'x',0},
{'y',0},
{'z',0}
};
int currentchar=0;
int letternum=0; //character position in char counting array
for (int i=0; i<inputlength; i++) {
currentchar=input[i];
letternum=0;
while (currentchar!=letterfrequencies[letternum][0]) {
letternum++;
}
printf(" Found a character ");
letterfrequencies[letternum][1]++; //Add to char counting array
printf("\n");
}
環路(我使用的是破發點Xcode調試),一切都按預期工作的第一次迭代。然而,在第一次迭代之後,該行:
letterfrequencies[letternum][1]++;
崩潰程序,說線程1:EXC_BAD_ACCESS(代碼= 2,地址= 0x7fff5fc2e84c)。如果我評論這條線,一切都會順利進行。 這可能是什麼原因造成的?
想當'currentchar'是一個空格時會發生什麼。您的代碼調用未定義的行爲。如果在'letterfrequencies'中找不到'currentchar',你應該採取一些措施。 –
僅僅是輸入a-z嗎? – BLUEPIXY
@Cool修復它的人。 – TheInnerParty