Home > Mobile >  Initialize **char array with known size in C
Initialize **char array with known size in C

Time:02-05

I want to initialize an array of strings such that the object is the type **char.

I know that I can do this via:


char **my_array = malloc( 3 * sizeof(char*));
for (int i = 0; i < (3); i  ) {
   my_array[i] = malloc(10 * sizeof(char));
}

sprintf(my_array[0], "first");
sprintf(my_array[1], "second");
sprintf(my_array[2], "third");

But it seems really cumbersome, especially because the strings are set before I compile. Is there a way to get (specifically a char ** type) with syntax more like:

char ** my_array = {"first", "second", "third"};

So that I have the property: printf(my_array[0]); returns first?

CodePudding user response:

Assuming the strings are fixed, you want an array of const char *:

const char *my_array[] = {"first", "second", "third"};

CodePudding user response:

char ** my_array is a pointer to a char pointer, it does not allocate any more memory. If you know from the beginning that you will have only three strings, and expect only strings of max 10 characters, you can allocate your array statically: char my_array[3][10]

  •  Tags:  
  • Related