I'm trying to create a function that prints out a sequence of letters in the alphabet in order given a parameter count. For example, if the count was four the output would be strings "a" "ab" "abc" "abcd". However, if the count was more than 26 it would loop around back to 'a', so the output for count 28 would be "a"....."abcdefghijklmnopqrstuvwxyzab". Below is the code I have written. When I try to run this code however I get a segmentation fault error on the line with
out[i][j] = let
and I am having some difficulty figuring out why.
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;
}
out[i].out. Just allocatecountelements the first time.sizeat any point.