Home > database >  how to initialize char *** from string liertal
how to initialize char *** from string liertal

Time:11-17

But I am wondering how to initialize char *** in c.
initialize char* :

char *test = "hello";
printf("tets[0]=%s\n",test);

The following is initialize char **.

char **test = (char *[]) {"hello", "world"};
   printf("tets[1]=%s\n",test[1]);

So far I tried to initialize char ***:

// char ***test = (*(char *[])) {{"hello"}, {"world"}};
//char ***test = ((char **)[]) {{"hello"}, {"world"}};

Intended to achieve, initialize a char*** using text string literal. Then i can use printf("tets[1]=%s\n",(*test)[1]) to print out world.

CodePudding user response:

It is possible to additionally create a compound literal which is simply an object of type char** which points to the first element of the array you defined in the question, and make the char *** point to this char ** object:

#include <stdio.h>

int main( void )
{
    char ***test = &(char**){ (char *[]){"hello", "world" } };

    printf( "test[1]=%s\n", (*test)[1] );
}

This program has the desired output world.

However, adding this additional layer of indirection does not make much sense. It would make more sense to simply use a char** instead of a char***, as you did in the code in your question.

CodePudding user response:

You can have compound literal containing compound literals.

char *test = "hello";
printf("tets[0]=%s\n",test);

char **test1 = (char *[]) {"hello", "world"};
   printf("tets[1]=%s\n",test1[1]);

char ***test2 = (char **[]){(char *[]) {"hello", "world"}, (char *[]) {"something", "else"}};
   printf("tets[1]=%s\n",test2[1][1]);

char **elem1 = (char *[]) {"hello", "world"};
char **elem2 = (char *[]) {"something", "else"};

char ***test3 = (char **[]){elem1, elem2};
   printf("tets[1]=%s\n",test2[1][0]);

CodePudding user response:

I can't come up with any scenario when such code would make any sense. Literally the only place in C where char*** can perhaps be justified, is when returning a pointer-to-pointer through a function parameter. Every other use of char*** is very likely caused by muddy or incorrect program design.

If you wish to implement a 2D array of pointers (without using structs, as would perhaps be a good idea), then the correct way would be to use a 2D array: char* array[X][Y]. And in case pointing at string literals, also make it const. Then you can point at that 2D array row by row:

Example of code that might actually make sense:

#include <stdio.h>

#define X 2
#define Y 2

int main()
{
  const char* (*strtable) [Y] = 
    (const char* [X][Y])
    {
      { "hello",   "world" },
      { "testing", "testing" },
    };

  for(size_t i=0; i<X; i  )
  {
    for(size_t j=0; j<Y; j  )
    {
      printf("%-10s ", strtable[i][j]);
    }
    printf("\n");
  }
}
  •  Tags:  
  • c
  • Related