c ++ files array搞砸了我的变量

时间:2015-02-25 14:00:30

标签: c++

我的程序不断产生分段错误。 我已将代码简化为以下内容:

#include <stdio.h>

void open_file(FILE** file)
{
        *file = fopen("test" , "wb");
        return;
}


int main ()
{
    int Tracks = 1;
    FILE* Files;
    int i = 1;

    Files = new FILE[Tracks + 1];

    printf("i = %d\n", i); //i = 1
    open_file(&Files + i);

    printf("i = %d\n", i); /i = 0
    fclose(*(&Files + i)); //Segmentation fault

    return 0;
}

我必须做一些非常愚蠢的指针错误,但对我来说我的指针 - 算术操作看起来很好......问题是,由于某些神奇的原因,变量i将其值更改为0.有人可以解释为我为什么??

提前致谢!

2 个答案:

答案 0 :(得分:4)

问题是operator precedence之一,其中address-of运算符的优先级高于加法运算符。这意味着你正在做,例如(&Files) + i,相当于(&Files)[i]

答案 1 :(得分:2)

fopen返回FILE *,因此您可能希望使用FILE *或FILE **数组来存储其中的许多内容。

此外,您必须在关闭之前检查要打开的文件。

#include <stdio.h>

void open_file(FILE** file)
{
    *file = fopen("test" , "wb");
    return;
}    

int main ()
{
    int Tracks = 1;
    FILE** Files = new FILE*[Tracks + 1];
    int i = 1;

    printf("i = %d\n", i); //i = 1
    open_file(&Files[i]);  // Will write at the address of the i-th element of Files.

    printf("i = %d\n", i); //i = 1

    // This have to be done for each element that correspond to an open file.
    // Add a for-loop should be considered.
    if (Files[i])          // Avoid segmentation fault
    {
        fclose(Files[i]);
        Files[i] = 0;      // So I know it is closed.
    }

    delete[] Files;
    return 0;
}

关于Files[i] = 0;,您可以查看here

关于魔术 i修改。 发生了什么:

void open_file(FILE** file)
{
    // Write file address or 0 at the given address.
    *file = fopen("test" , "wb");
    return;
}    

int main ()
{
    int Tracks = 1;
    FILE* Files = new FILE[Tracks + 1];  // Files at address a
    int i = 1;                           // i probably at address a + sizeof(FILE*)

    printf("i = %d\n", i); // i = 1

    // here i = 1 so &Files + i = &Files + 1 = address of i.
    open_file(&Files + i); // Call to open_file with the address of i !

    // open_file failed and write 0 to the given address.
    printf("i = %d\n", i); // i = 0
}