0

I am trying to make function that fills array of strings with lines from file, but the compiler (GCC) still giving me a warning. Than if I try to run compiled app, it gives me "Segmentation fault" error
Source code:

main

#include <stdio.h>

#include "getAdresses.h"

int main(int argc, char **argv){
        char adresses[1024][128];
        getAdresses(adresses);
        printf("%s", adresses[1]);

}

getAdresses

include <stdio.h>

int getAdresses(char **adresses){
        FILE *fr;
        fr = fopen("adresses", "r");
        int i = 0;
        while(adresses[i-1][0] != EOF){
                fscanf(fr, "%s\n", &adresses[i]);
                i++;
        }
}

It's giving me this error:

main.c: In function ‘main’:
main.c:9:2: warning: passing argument 1 of ‘getAdresses’ from incompatible pointer type [enabled by default]
In file included from main.c:3:0:
getAdresses.h:1:5: note: expected ‘char **’ but argument is of type ‘char (*)[128]’
Jakub Tětek
  • 161
  • 1
  • 1
  • 7
  • And so a two-diemensional array strikes again... – Dariusz Oct 14 '13 at 16:50
  • AFAIKT it's "just" a warning, so the code should at least work. I just think it's not a good idea to read unbound from the file. What do you think will happen if you try to read more then 1024 "strings"? – Friedrich Oct 14 '13 at 16:52
  • the compiler told you what you did wrong. Its a warning because its possible the you mean to pass the wrong type, but if you dont understand the warning then you should treat it as fatal. – pm100 Oct 14 '13 at 16:56

3 Answers3

1

First of all you have done the typical mistake: char ** is not the same as a char (*)[128]. The latter is the type of adresses.

You get the segmentation fault when you try to dereference it in line

while(adresses[i-1][0] != EOF)

Aside from the fact that adressing [i-1] for i = 0 will give you bad results you should define your function as

int getAdresses(char (*adresses)[128])

to be able to pass your two dimensional array correctly and fscanf should scan into your actual line buffer and if you are reading line by line use fgets:

while(fgets(adresses[i], 128, fr)) i++;
Sergey L.
  • 21,822
  • 5
  • 49
  • 75
0

when you pass adresses[1024][128] to a function, the compiler will only do one step of decay, and the parameter type should be char (*)[128] instead of char ** .

You also need to pass its first dimension to the function, which means

int getAdresses(char (int (*arr)[128], int x)

check the c-faq for a detailed explanation for this issue.

Zac Wrangler
  • 1,445
  • 9
  • 8
0

The array you allocated declaring

char adresses[1024][128]

is actually a char* (it isn't but it's much closer to it than to char**).

The double diemension accessor is actually just a syntactic sugar for [x+y*width].

To pass the array as a parameter use:

int getAdresses(char (*adresses)[128])
Dariusz
  • 21,561
  • 9
  • 74
  • 114