0

I need help understanding what char*** means and how do I initialize a variable that is of type char***.

For example, if there is a function that reads the lines of a file, while keeping track of the number of lines and printing out each line with its corresponding number:

void read_lines(FILE* fp, char*** lines, int* num_lines){}

What would char*** represent in this case and how would I initialize the variable lines?

Christina
  • 61
  • 6
  • https://stackoverflow.com/a/1768382/920069 – Retired Ninja Jun 01 '19 at 03:23
  • [Read a book first](https://stackoverflow.com/q/562303/995714) instead of just asking here on SO – phuclv Jun 01 '19 at 03:57
  • Possible duplicate of [What does \*\* mean in C++?](https://stackoverflow.com/questions/23537889/what-does-mean-in-c) – phuclv Jun 01 '19 at 03:58
  • 3
    Beware: being accused of being a [Three-star Programmer](http://wiki.c2.com/?ThreeStarProgrammer) is not a compliment. – Jonathan Leffler Jun 01 '19 at 04:03
  • It usually means you need to rearrange or refactor your code to provide a return of some type that can be assigned, etc.. so has to no longer be a Three-star Programmer. (that said, there are some instances with pointer where it may be a reasonable choice, such as where the address of a *poiner-to-pointer-to-type* is required) In your case you could change your declaration to `char **read_lines(FILE* fp, char** lines, int* num_lines){}` and return a pointer to the modified `lines` for assignment back in the caller. – David C. Rankin Jun 01 '19 at 05:01

2 Answers2

2

It's a pointer-to-pointer-to-pointer-to-char. In this case, it's very likely to be an output parameter. Since C passes arguments by value, output parameters require an extra level of indirection. That is, the read_lines function wants to give the caller a char**, and to accomplish that via an output parameter, it needs to take a pointer to a char**. Likely all you'd need to do to invoke it is:

char** lines = null;
int num_lines;
read_lines(fp, &lines, &num_lines);

Also see C Programming: malloc() inside another function.

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
2

I need help understanding what char*** means ...

The char*** type is a pointer. A pointer to a char **. p as pointer to pointer to pointer to char

char*** p;

... and how do I initialize a variable that is of type char***.

char*** p1 = NULL;  // Initialize p with the null pointer constant.

char *q[] = { "one", "two", "three" };
char*** p2 = &q;  // Initialize p2 with the address of q

char ***p3 = malloc(sizeof *p3);  // Allocate memory to p3.  Enough for 1 `char **`.
....
free(p3); // free memory when done.
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256