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]);
  }
BEPP
  • 875
  • 1
  • 12
  • 36
  • `void print_str(char str[][],int count)` --> `void print_str(char str[][MAX_STR_LEN],int count)` – BLUEPIXY Jul 26 '16 at 05: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](https://stackoverflow.com/questions/486075/passing-an-array-of-strings-as-parameter-to-a-function-in-c), in particular the *second* answer. – WhozCraig Jul 26 '16 at 05:36
  • @Naveen Kumar I'm wondering what compiler were you using - because most I know of wouldn't even compile this code. – AnArrayOfFunctions Jul 26 '16 at 21:36

3 Answers3

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);
msc
  • 33,420
  • 29
  • 119
  • 214
1

Use

void print_str(char str[][MAX_STR_LEN], int count);
R Sahu
  • 204,454
  • 14
  • 159
  • 270
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.

Chetan Raikwal
  • 138
  • 1
  • 1
  • 9