0

In the following program i just try to copy some string to the array and print it in another function.

I am getting segmentation fault .Could someone point out what i did wrong ?

  #include <stdio.h>
  #include <string.h>
  #define MAX_STR_LEN 20

  void print_str(char str[][],int count);

  int main()
  {
      char str[2][MAX_STR_LEN];
      strncpy(str[0],"hello",MAX_STR_LEN);
      strncpy(str[1],"world",MAX_STR_LEN);
      print_str(str,2);
      return 0;
  }
  void print_str(char str[][],int count)
  {
      int i;
      for(i=0;i<count;i++)
      printf("%s\n",str[i]);
  }
3
  • void print_str(char str[][],int count) --> void print_str(char str[][MAX_STR_LEN],int count) Commented Jul 26, 2016 at 5:35
  • 2
    If this isn't documented in whatever tutorial or book you're using, find something else. The parameter should be char str[][MAX_STR_LEN]. All but the most dominant dimension of an array of arrays as a parameter must be declared. There are probably hundreds of duplicates of this problem in one form or another, but generally the title is so diverse it is difficult to find them. One that is close would be this question, in particular the second answer. Commented Jul 26, 2016 at 5:36
  • @Naveen Kumar I'm wondering what compiler were you using - because most I know of wouldn't even compile this code. Commented Jul 26, 2016 at 21:36

3 Answers 3

3

We need to specify the column size mandatory when passing a 2D array as a parameter.

So, You should declare your function like this:

void print_str(char str[][MAX_STR_LEN],int count);
Sign up to request clarification or add additional context in comments.

Comments

1

Use

void print_str(char str[][MAX_STR_LEN], int count);

Comments

1

Provide the second dimension length in a 2-D array in C always. First dimension length is optional if you are declaring a 2-D array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.