我正在嘗試創建一個函式,該函式按給定引數計數的順序列印出字母表中的字母序列。例如,如果計數為 4,則輸出將為 strings "a" "ab" "abc" "abcd"。但是,如果計數超過 26,它將回圈回到“a”,因此計數 28 的輸出將是"a"....."abcdefghijklmnopqrstuvwxyzab"。下面是我寫的代碼。但是,當我嘗試運行此代碼時,出現分段錯誤錯誤
out[i][j] = let
我很難弄清楚為什么。
char **sequences(int count) {
int letter = 0;
char **out = (char**)calloc(10, sizeof(char*));
char **array = NULL;
int size = 0;
int cap = 10;
char let;
for (int i = 0; i < count; i ) {
if (size == cap) {
cap *= 2;
array = (char **)realloc(out, cap*sizeof(char *));
if (array != NULL) {
out = array;
} else {
break;
}
}
for (int j = 0; j < i; j ) {
if (letter < 26) {
let = 97 letter;
printf("%c\n", let);
out[i][j] = let;
printf("%c\n", out[i][j]);
letter ;
size ;
} else {
letter = 0;
let = 97 letter;
printf("%c\n", let);
out[i][j] = let;
printf("%c\n", out[i][j]);
letter ;
size ;
}
}
}
return out;
}
int main(void) {
char** first;
char** second;
first = sequences(1);
printf("sequences[0] should be \"a\", got: %s\n", sequences[0]);
second = sequences(28);
printf("sequences[27] should be \"ab...yzab\", got: %s\n", sequences[27]);
return 0;
}
uj5u.com熱心網友回復:
主要問題是您永遠不會為out[i]. 您可以使用calloc(i 1, sizeof(char)). 我為空終止符添加 1。
沒有必要繼續成長out。realloc()你知道最終的大小是count,所以一開始就分配那么多。
您不需要單獨的letter計數器。您可以使用模算術在 26 處折回。
char **sequences(int count) {
char **out = malloc(count * sizeof(char*));
if (out == NULL) {
abort();
}
for (int i = 1; i <= count; i ) {
out[i-1] = calloc(i 1, sizeof(char));
if (out[i-1] == NULL) {
abort();
}
for (int j = 0; j < i; j ) {
char let = 'a' (j % 26);
out[i][j] = let;
printf("%c\n", let);
}
}
return out;
}
uj5u.com熱心網友回復:
答案很簡單。您分配了一個指標陣列,但沒有為字串分配任何空間。當您使用時,calloc所有指標都是 NULL。
在這一行(以及您使用的所有其他行out[i][j])
out[i][j] = let;
你取消參考 NULL 指標。這是未定義的行為( UB),在您的情況下,它表示為 SegFault 。
uj5u.com熱心網友回復:
不確定分配是什么,但您可以完全放棄分配,只需直接跳到輸出,如果您只需要這樣,IMO 會更簡單一些:
void printSequences(size_t count)
{
for (size_t i=0; i<count; i )
{
for (size_t j=0; j<=i; j )
{
putchar('a' (j % 26));
}
putchar('\n');
}
putchar('\n');
}
作業演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/487776.html
上一篇:我可以在我的Angular應用程式中用什么替換tap方法?
下一篇:這fscanf行為是否不一致?
