What is the right way to initialize char**
? I get coverity error - Uninitialized pointer read (UNINIT) when trying:
char **values = NULL;
or
char **values = { NULL };
There are two ways to declare string array - declaration without size and declare with size. There are two ways to initialize string array - at the time of declaration, populating values after declaration. We can do different kind of processing on string array such as iteration, sorting, searching etc.
Create an array of empty strings that is the same size as an existing array. It is a common pattern to combine the previous two lines of code into a single line: str = strings(size(A)); You can use strings to preallocate the space required for a large string array.
This example program illustrates initialization of an array of C strings.
#include <stdio.h> const char * array[] = { "First entry", "Second entry", "Third entry", }; #define n_array (sizeof (array) / sizeof (const char *)) int main () { int i; for (i = 0; i < n_array; i++) { printf ("%d: %s\n", i, array[i]); } return 0; }
It prints out the following:
0: First entry 1: Second entry 2: Third entry
Its fine to just do char **strings;
, char **strings = NULL
, or char **strings = {NULL}
but to initialize it you'd have to use malloc:
#include <stdlib.h> #include <stdio.h> #include <string.h> int main(){ // allocate space for 5 pointers to strings char **strings = (char**)malloc(5*sizeof(char*)); int i = 0; //allocate space for each string // here allocate 50 bytes, which is more than enough for the strings for(i = 0; i < 5; i++){ printf("%d\n", i); strings[i] = (char*)malloc(50*sizeof(char)); } //assign them all something sprintf(strings[0], "bird goes tweet"); sprintf(strings[1], "mouse goes squeak"); sprintf(strings[2], "cow goes moo"); sprintf(strings[3], "frog goes croak"); sprintf(strings[4], "what does the fox say?"); // Print it out for(i = 0; i < 5; i++){ printf("Line #%d(length: %lu): %s\n", i, strlen(strings[i]),strings[i]); } //Free each string for(i = 0; i < 5; i++){ free(strings[i]); } //finally release the first string free(strings); return 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With