user2793574
user2793574

Reputation: 13

Segmentation fault when printing out arrays

This is part of the program I am working on, it is copying the file opened and then put it into an array (file1). However, I am getting a segmentation fault when I try to print out the content of the file1.

I had tried to set the MAX_MAC_ADD to 50 and BIG_NUM to 30000 such that it is big enough to sustain the file from fgets().

The file which I am opening has 4 parts, each separate by a 'tab'

e.g. 1one 1two 1three 1four 2one 2two 2three 2four

char    file1[MAX_MAC_ADD][BIG_NUM];
int         num_MAC = 0;

char    *Programe_Name;

int saperate_fields1(char line[])
{
int i = 0;
int f = 0;

while(line[i] != '\0' && line[i] != '\n')
{
    int c = 0;

    while(line[i] != '\t' && line[i] != '\0' && line[i] != '\n')
    {
        file1[f][c] = line[i];
        ++c;
        ++i;
    }
    file1[f][c] = '\0';

    ++f;
    if(f == (MAX_MAC_ADD-1))
    {
        break;
    }
    ++i;
}
return f,i;
}

void read_file1(char filename[])
{
//OPEN FOR READING
FILE    *fp = fopen(filename,"r");

if(fp == NULL)
{
    printf("%s: cannot open '%s'\n", Programe_Name, filename);
    exit(EXIT_FAILURE);
}
char    line[BUFSIZ];
while(fgets(line, sizeof line, fp) != NULL)
{
    saperate_fields1(line);     //SAPERATE INTO FIELDS
    num_MAC = num_MAC + 1;
    printf("%d times\n", num_MAC);
}
fclose(fp);
printf("line is:\n%s\n", line); //TO CHECK WHERE DO THE PROGRAM STOP READING
printf("file1 is:\n%s\n", file1);
}

Upvotes: 1

Views: 473

Answers (1)

Dietmar Kühl
Dietmar Kühl

Reputation: 153802

You pass a pointer to an array of chars to the format specifier %s which expects a pointer to a char. If you want to print your array of arrays of char you need to print the elements individually, e.g.:

for (int i = 0; i != end; ++i) {
    printf("file1[%d]='%s'\n", i, file1[i]);
}

Upvotes: 1

Related Questions