Pointer issues with basic C file I/O program
-
21-08-2019 - |
Question
#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?
Solution
You are trying to print lorem_ipsum[i]
as if it were a string. lorem_ipsum
is a string, so lorem_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.
OTHER TIPS
You're passing a char
(lorem_ipsum[i]
) to the fscanf
function, which expects a char*
as the argument.
You might want to use lorem_ipsum
or lorem_ipsum+i
if you really want to strip the first i
characters off.
Can you explain what you're trying to do in the for loop?
It seems to me that you are trying to read the file line by line and then print the line. However, when you do the printf("%s", lorem_ipsum[i]), you are sending a character, not a string.