I have a pointer to an array of char and I need to print the entire array (not one after the other but the entire array). I have the error: zsh: segmentation fault. I don't understand why.
My code take a text from stdin and put the chars in an array. If the first array char_array isn't big enough I put them in the second one called bigger_array.
int main() {
int c;
int index = 0;
size_t size = 100;
char *char_array = malloc(size * sizeof(char));
if (char_array != 0) {
while ((c = getchar()) != EOF && index < size) {
char_array[index] = c;
index++;
}
size_t newSize = size * 100;
char *bigger_array = realloc(char_array, newSize * sizeof(char));
if (bigger_array != 0) {
bigger_array = char_array;
while ((c = getchar()) != EOF && index < newSize) {
bigger_array[index] = c;
index++;
}
size = newSize;
}
}
printf(*char_array);
return 0;
}
bigger_arrayeven when the first array had enough elements for the input.char_arraywhenchar_array == 0is bad.