You have just a pointer, nothing more. You need to allocate memory using malloc()
.
Actually, you need first to allocate memory for pointers, then allocate memory for strings.
N lines, each M characters long:
char** lines = malloc(sizeof(*lines) * N);
for (int i = 0; i < N; ++i) {
lines[i] = malloc(sizeof(*(lines[i])) * M);
}
You are also taking an address and then immediately dereference it - something like*(&foo)
makes little to no sense.
For updated code
Oh, there is so much wrong with that code...
- You need to include
stdlib.h
to use malloc()
lines
is undeclared. The char** lines
is missing before loop
if
in loop checks whether line_no
is 0
. If it is, then it allocates lines
. The problem is, variable line_no
is 0
- sizeof(*lines)
times 0 is still zero. It allocates no memory.
- But! There is
++line_no
at the beginning of the loop, therefore line_no
is never 0, so malloc()
isn't called at all.
lines[line_no-1] = buffer;
- it doesn't copy from buffer
to lines[line_no-1]
, it just assigns pointers. To copy strings in C you need to use strcpy()
fgets()
adds new line character at the end of buffer - you probably want to remove it: buffer[strcspn(buffer, "\n")] = '\0';
- Argument
len
is never used.
char buffer[buffer_length];
- don't use VLA
- It would be better to increment
line_no
at the end of the loop instead of constantly calculating line_no-1
- In C, casting result of
malloc()
isn't mandatory
- There is no check, if opening file failed
- You aren't freeing the memory
Considering all of this, I quickly "corrected" it to such state:
void read_file(char const* name)
{
FILE* file = fopen(name, "r");
if (file == NULL) {
return;
}
int buffer_length = 1024;
char buffer[1024];
char** lines = malloc(0);
int line_no = 0;
while (fgets(buffer, buffer_length, file)) {
buffer[strcspn(buffer, "\n")] = '\0';
printf("---%s\n", buffer);
lines = realloc(lines, sizeof (*lines) * (line_no+1));
lines[line_no] = malloc(sizeof (*lines[line_no]) * buffer_length);
strcpy(lines[line_no], buffer);
printf("-------%s--------\n", lines[line_no]);
++line_no;
}
fclose(file);
for (int i = 0; i < line_no; ++i) {
free(lines[i]);
}
free(lines);
}