#include <stdio.h> #include <stdlib.h> int main() { FILE *fp = fopen('lr.txt', 'r'); fseek(fp, 0L, SEEK_END); int size = ftell(fp); fseek(fp, 0L, SEEK_SET); char *lorem_ipsum; int i = 0; lorem_ipsum = (char*) malloc(sizeof(char) * size); while(fscanf(fp, '%s\n', lorem_ipsum) != EOF) { printf('%s', lorem_ipsum[i]); i++; } fclose(fp); return 0; }
This program compiled and ran, however, what happened was that I got a segfault and I don’t know quite exactly what’s wrong with this program. Could somebody help me with the pointer error I got?
You are trying to print
lorem_ipsum[i]as if it were a string.lorem_ipsumis a string, solorem_ipsum[i]is just a character.The segfault happens because printf looks at the value of the character at
lorem_ipsum[i]and interprets it as a char* pointer (a string). Naturally, the value of the character doesn’t correspond to a valid, allocated memory address.