当查看FILE流的地址时,为什么地址与原始指针的地址大不相同

When looking at the address of a FILE stream, why is the address so much different than that of the original pointer?

本文关键字:地址 为什么 原始 大不相同 指针 FILE      更新时间:2023-10-16

请原谅我对这里完全没有任何理解,只是深入到C++中。所以本质上,我只是想看看我是否能想出如何使用putc正确地将字符写入文件。我想确保我理解每一步。

现在,当我查看最初为文件声明指针时使用的地址空间,并将指针传递给将流写入文件的不同函数后,我注意到地址空间与原始函数的地址空间完全不同,甚至在长度上也是如此。我仍然试图完全理解指针,但如果没有任何干预,很难告诉你你误解了什么,我知道我必须这样做。这是代码,不要介意我在Qtcreator中这样做。链接有帮助,但请不要只是复制意大利面一些C++信息页面上的指针。我读过。

#include <QCoreApplication>
#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;
void stream_writer(FILE & stream)
{
    int     c1='A',
            c2='B',
            c3='C',
            nl='n';
    cout << &stream << endl;
    putc(c1, &stream);
    putc(nl, &stream);
    cout << "written to testfile" << endl;
    fclose(&stream);
    putc(c2, stdout);
    putc(c3, stdout);
    putc(nl, stdout);
}
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    FILE* testfile;
    testfile = fopen("testfile.txt", "wt");
    if (testfile != NULL )
    {
        cout << &testfile << endl;
        cout << testfile << endl;
        stream_writer(*testfile);
    }
    else
    {
        cout << "Unable to open filen";
    }
    return a.exec();
}

运行代码后控制台输出的示例:

0x7ffff6ed478
0x138a200
0x138a200
写入测试文件
BC

void stream_writer(FILE & stream)

在这里,您收到了对FILE对象的引用。

cout << &stream << endl;

在这里,您通过引用打印FILE对象的地址。

FILE* testfile;

在这里,您正在声明一个指向FILE的指针。

cout << &testfile << endl;

您正在打印指针的值。

stream_writer(*testfile);

在这里,您将取消引用的指针作为对象引用传递给被调用的函数。

如果所有这些都具有相同的价值,那将是令人惊讶的。

你的期望是错的。

cout << &testfile << endl;正在打印FILE指针本身的地址:0x7ffff6aed478

cout << testfile << endl;正在打印指针指向的地址:0x138a200

地址0x7ffff6aed478的内存是FILE指针的存储位置,其值为0x138a200。

地址0x138a200处的内存是实际FILE对象的分配位置,此处的值对应于结构FILE{…}中的数据

stream_writer(*testfile);您正在取消引用以获取FILE对象,通过引用将其传递给stream_writer()。cout << &stream << endl;然后您将再次打印同一FILE对象的地址。因此,第三行输出为0x138a200