0

I am trying to pass a char matrix as a parameter to another function but the programme keeps stopping, without giving me any error. I have read the matrix from a file which contains the following (each value on different line): 6 AFAA26 7A4255 1C80B6 2C158F DA8204 5A408A

My code:

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

void read(char s[100][100],int n)
{
    int i;
    for(i=0;i<n;i++)
        printf("%s\n",s[i]);
}

int main()
{
  random();
  FILE *fp=fopen("p1","r");
  int n,i,j;
  fscanf(fp,"%d",&n);
  char s[20][10];
  for(i=0;i<n;i++)
      fscanf(fp,"%s",&s[i]);
  fclose (fp);
  read(s,n);
  return 0;
}

note: by writing "for(i=0;i<n;i++) printf("%s\n",s[i]);" in the main function it reads me correctly the values from the file.

Thank you!

selbie
  • 100,020
  • 15
  • 103
  • 173
  • 1
    Are you getting any warning from you compiler? – kabanus Apr 21 '19 at 09:52
  • 2
    Don't name your function `read`. There's already a standard POSIX function called `read`. The irony being that your `read` function doesn't actually read anything from. – selbie Apr 21 '19 at 09:55
  • when `read` tries to access `s[7]`, how are you expecting the compiler to know where that string begins? The `read` function has no idea that each string in `s` is 10 characters long. – David Schwartz Apr 21 '19 at 09:56

1 Answers1

3

Your sizes from the declared array and the parameter do not match.

You can either declare the same dimensions, perhaps using a #define to avoid duplication, or have a look at this question for other (maybe better) alternatives.

Paul92
  • 8,827
  • 1
  • 23
  • 37