-1

I have a readfile function called by main. The criteria is I have to pass char** into readfile, and I have to allocate and initialize this argument inside readfile. I am a bit confused about how to deal with char** in a subfunction.

void main()
{
      char** data;
      readfile(data);
}

void readfile(char** data)
{
   data = (char**)malloc(1000);   //give me Segmentation fault
   data = (char*)malloc(1000); //give me " warning: assignment from incompatible pointer type" during compliation.
   data = (char)malloc(1000); //give me "warning: cast from pointer to integer of different size" during compilation.

}

I tried to cast a pointer to it first e.g. char* pdata = *data; and I can use pdata ok.

How can I allocate this variable inside the readfile function?

Jay
  • 9,585
  • 6
  • 49
  • 72
user3037484
  • 25
  • 1
  • 7

2 Answers2

1

There are two solutions:

  1. Allocate memory in main

  2. Pass the address of the pointer like this:

    void main()
    {
        char** data;
        readfile(&data); //notice the pass of data adress to the function
    }
    
    void readfile(char*** data)  //notice the extra * operator added
    {
        *data = malloc(1000); 
    }
    
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
Igor Pejic
  • 3,658
  • 1
  • 14
  • 32
  • 1
    Thanks for the reply. The requirement is to use char** as a param and allocate the memory inside the function. And I have to be able to bring the array back to main. – user3037484 Aug 27 '14 at 19:02
  • 1
    Yeah that's very cute, but it can't be done if you need to pass a pointer to a pointer. If you have a pointer to a pointer you parameter has to be char*** data. – Igor Pejic Aug 27 '14 at 19:07
  • Thanks. I will allocate memory in main then. I can just do char* data instead. And it's working. – user3037484 Aug 27 '14 at 19:13
0

Maybe you want char*data=NULL; in main then call readfile(&data); there. Any change to formal argument data inside readfile is not propagated to the caller (because C has a call by value semantics when passing arguments).

Also, you should always test the result of malloc like e.g.

data = malloc(1000);
if (!data) { perror("malloc data"); exit(EXIT_FAILURE); };

and you probably should initialize the obtained memory zone, perhaps using

memset (data, 0, 1000);

or simply use calloc to get zeroed memory.

If you pass &data from main declare your formal argument of readfile as char**ptr and do inside readfile something like *ptr = malloc(1000); etc...

BTW, did you consider using getline(3)? It probably is relevant.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547