当查看FILE流的地址时,为什么地址与原始指针的地址大不相同
When looking at the address of a FILE stream, why is the address so much different than that of the original pointer?
请原谅我对这里完全没有任何理解,只是深入到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
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 为什么我在leetcode上收到AddressSanitizer:地址0x602000000058上的堆缓冲区溢出错误
- 为什么指针不写入类的地址?
- 为什么 ulimit -v 在 Clang 的地址清理器下不起作用?
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 为什么未命名的结构内联变量在每个翻译单元中没有相同的地址?
- 为什么我可以将变量存储在不是其最小对齐方式的倍数的地址?
- 为什么C++总是显示十六进制内存地址,而不仅仅是整数?
- 为什么两个矢量元素的地址有这么大的差距?
- 如果 const 不分配内存,为什么我可以获取 const 的地址?
- 为什么同一个变量的内存地址不同?
- 为什么成员函数地址离自由函数这么远?
- 为什么我得到以下代码地址清理器:未知地址错误的SEGV
- 堆栈分配的类类型.为什么两个 ID 实例的地址相同?
- 为什么每次执行时函数的地址都不同?
- 为什么地址相同?
- 为什么存储在数组中的地址值与其自己的地址相同,它应该指向某个不同的地址(&arr[0])?
- 为什么 C++ 地址中的矢量无法通过原始指针访问
- 为什么下面的代码段返回指针指向的值而不是指针的地址?
- 为什么使用存储在虚拟方法表中的地址调用虚拟函数的函数会返回垃圾?