-2

I'm making a shell for my school, and I'm actually working on pipes |. In order to parse, I need to put some things in a char ***. How do I malloc a char ***?

WayneXMayersX
  • 338
  • 2
  • 10
Eindall
  • 57
  • 1
  • 8
  • 1
    In general it's difficult to reply to questions asking how to allocate pointers, given that they can be used to point to different kind of objects (are you pointing straight to another pointer? or are you allocating an array of double pointers? or something else entirely?). You should clarify your question if you want to obtain meaningful answers. Also, remember that [being called a Three-Star Programmer is not usually a compliment](http://wiki.c2.com/?ThreeStarProgrammer). If you feel the need to use triple indirection you should probably stop for a moment to rethink your solution. – Matteo Italia May 21 '17 at 16:58

1 Answers1

0

malloc doesn't care what type you are going to use its return value as. So you can malloc a char*** just like you malloc anything else.

Most of time time, you will be trying to dynamically allocate an array of some time T, which you will need to store in a variable of type T*. So if you need an array of char** (say, an array of argv vectors), you would store them in a variable of type char***. (T is char** so T* is (char**)* which is char***.)

The general form for doing malloc is:

T* result = malloc(number_of_elements * sizeof(*result));

If you write the malloc call like that, then you can change the type of the result without changing the malloc call.

Remember that the memory region returned by the malloc is not initialized in any way. If you are allocating an array of arrays, you might want to ensure that the allocated memory is initialized to zeros using

T* result = calloc(number_of_elements, sizeof(*result));

In any event, you will then need to actually allocate the subarrays individually.

rici
  • 234,347
  • 28
  • 237
  • 341