1

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?

11
  • 2
    Where are you allocating memory for the struct? Commented May 21, 2020 at 17:16
  • 1
    No repro. repl.it/@robertwharvey/LoathsomeCostlyReentrant Commented May 21, 2020 at 17:16
  • @RobertHarvey hi , u mean it works? no repro? you mean i should just put a link to executable online ide? Commented May 21, 2020 at 17:18
  • Well... I'm inclined to agree with Tony. You're not allocating memory for struct s_string_array *d; Commented May 21, 2020 at 17:19
  • So it might be UB. Commented May 21, 2020 at 17:19

1 Answer 1

4

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Good example of using char ** without using dynamic allocated memory.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.