I'm having trouble with allocating memory with

2019-07-28 18:32发布

问题:

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.

回答1:

void allocate(char ***strings, int size)
{
   int i;

   // Here you allocate "size" string pointers...
   *strings = malloc( sizeof (char*) * size);

   // for each of those "size" pointers allocated before, here you allocate 
   //space for a string of at most MAX_STRING_LEN chars...
   for(i = 0; i < size; i++)      
      (*strings)[i] = malloc( sizeof(char) * MAX_STRING_LEN);

}

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:

 int main()
{
    int ***my_variable; 
} 

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

void f(int ****my_param)

and whenever you want to use it inside the function, use the same way as you would use in main with this little change:

(*my_param) = //some code

by using (*my_param) is the same as if you were using to my_variable in main



回答2:

You need

*strings = malloc(sizeof(char *) * 10); // Here is the array
(*strings)[0] = malloc(MAX_STRING_LEN);
strcpy((*strings)[0], "The first person");
printf("First person is %s\n", (*strings)[0]);

Dunno where size comes in