I'm having a great deal of difficulty with pointers. What I am trying to accomplish sounds, to my ears, rather simple: I want to define a multi-dimensional char array, but not its size, and then have a second method allocate the necessary memory, and fill it up with the requested data.
Now, I've tried for countless hours to accomplish this, searched with Google until my eyes were dry and I still haven't been able to fix it. As such I was hoping any of you had any insight how this would be possible.
What I am imagining, is to define a pointer char** files
, and a counter int total_files
that will be used my the method print_files()
. Print files will then calloc and malloc the variable, and then we'll fill it up with relevant data.
Now in the code below, I have attempted this; however, at runtime I just get the magnificently detailed message: "Segmentation fault (core dumped)". Upon debugging with GDB it points at:
13 *files[i] = malloc(sizeof(char) * 100);
Now, this is for a introductory course to C programming (for Linux), and you might see numerous errors here. I do however, thank you for your time. I had no issues getting the code to work without the method / pointers, so I'm sure I might just be mixing up the syntax somehow.
#define _SVID_SOURCE
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<dirent.h>
#include <time.h>
int print_files(char*** files, int* total_files) {
int size = 10;
**files = calloc(size, sizeof(char *));
for(int i = 0; i < size; i++) {
*files[i] = malloc(sizeof(char) * 100);
}
*total_files = size;
}
int main() {
char** files;
int num_files;
num_files = 0;
printf("-- Start print_files\n");
print_files(&files, &num_files);
printf("-- end print_files, number of files: %d\n", num_files);
for(int i = 0; i < num_files; i++)
printf("Out: %s\n", files[i]);
printf("total_files=%d\n", num_files);
return 0;
}
**files = calloc(size, sizeof(char *));
This assumes that not only files
points to valid memory, but the value at that memory is also a valid pointer pointing to a pointer, which will be changed.
The problem is
char** files;
...
print_files(&files, &num_files);
&files
is a valid pointer, but (**(&files))
(as dereferenced by print_files
) is an illegal deference because files
has not been initialized.
That print_files
line should probably read
*files = calloc(size, sizeof(char *));
.
There is also a problem with
*files[i] = malloc(sizeof(char) * 100);
which is equivalent to
*(files[i]) = malloc(sizeof(char) * 100);
I think you probably mean
(*files)[i] = malloc(sizeof(char) * 100);