cpointersstructcharc99

How to print the contents of char**?


I have a structure defined as a char** array containing strings. I don't know how to run printf on its contents.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#ifndef STRUCT_STRING_ARRAY
#define STRUCT_STRING_ARRAY
typedef struct s_string_array
{
    int size;
    char** array;
} string_array;
#endif


void my_print_words_array(string_array* param_1)
{
    int len = param_1->size;
    char **d = param_1->array;


    for(int i = 0 ; i < len;i++){
        printf("%s\n", d[i]);
    }
}

int main(){
    struct s_string_array *d;
    d->size = 2;
    
    char **my_arr = (char *[]){"hello", "world"};//this init is fine
    d->array = my_arr;
    my_print_words_array(d);
    return 0 ;

}

The main function gives me segfault error. What's wrong?


Solution

  • There is no sense to declare a pointer to the structure

    struct s_string_array *d;
    

    moreover that is not initialized and has indeterminate value that further is a reason of undefined behavior.

    What you are trying to achieve is the following

    #include <stdio.h>
    
    typedef struct s_string_array
    {
        int size;
        char** array;
    } string_array;
    
    void my_print_words_array( const string_array *param_1 )
    {
        for ( int i = 0; i < param_1->size; i++ )
        {
            puts( param_1->array[i] );
        }
    }
    
    int main( void )
    {
        string_array d =
        {
            .size = 2,
            .array = (char *[]){"hello", "world"}
        };
    
        my_print_words_array( &d );
    
        return 0 ;
    
    }
    

    The program output is

    hello
    world