I am having trouble with the allocating memory part of my program. I am supposed to read in a file that contains a list of names then allocate memory for them and store them in the allocate memory. This is what I have so far, but I keep getting a segmentation fault when I run it.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_STRING_LEN 25
void allocate(char ***strings, int size);
int main(int argc, char* argv[]){
char **pointer;
int size = atoi(argv[1]);
allocate(&pointer, size);
}
/*Will allocate memory for an array of char
pointers and then allocate those char pointers with the size of MAX_STRING_LEN.*/
void allocate(char ***strings, int size){
**strings = malloc( sizeof (char) * MAX_STRING_LEN);
}
This is currently not working because I am given a seg fault. Thanks a lot for the help in advance.
So, if you pass size as 10...
In your main you will have space for 10 strings (pointer[0] to pointer[9]).
And each of those strings can have up to 24 characters (don't forget the null terminator)...
Pointers are a little tricky but here is a trick to deal with them:
Lets say you have your main like this:
and you know how to operate in my_variable inside main...
To use it in a function you do as following:
add an extra * in the parameter
and whenever you want to use it inside the function, use the same way as you would use in main with this little change:
by using (*my_param) is the same as if you were using to my_variable in main
You need
Dunno where
size
comes in