简体   繁体   English

打印出数组时出现分段错误

[英]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 ). 这是我正在处理的程序的一部分,它正在复制打开的文件,然后将其放入数组( file1 )。 However, I am getting a segmentation fault when I try to print out the content of the file1 . 但是,当我尝试打印出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() . 我试图将MAX_MAC_ADD设置为50,将BIG_NUM设置为30000,以使其足以容纳fgets()的文件。

The file which I am opening has 4 parts, each separate by a 'tab' 我要打开的文件有4个部分,每个部分都由一个“标签”分开

eg 1one 1two 1three 1four 2one 2two 2three 2four 例如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);
}

You pass a pointer to an array of char s to the format specifier %s which expects a pointer to a char . 您将指向char数组的指针传递给格式说明符%s ,该说明符期望指向char的指针。 If you want to print your array of arrays of char you need to print the elements individually, eg: 如果要打印char数组,则需要单独打印元素,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM