Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Initialize **char array with known size in C

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading