gpt4 book ai didi

c++ - 我想我没有完全理解指针,但为什么这里的输出有所不同?

转载 作者:行者123 更新时间:2023-11-28 05:17:13 25 4
gpt4 key购买 nike

下面是我的代码片段。基本上,我想知道为什么当我单独打印 contextFile[0]contextFile[1] 与通过 for 打印时,输出会有所不同环形。

contextfile.txt(在本例中是 target_file_name 的值)中,我有以下内容:

hickory dickory dot had a little farm you feel me.

代码如下:

cin >> target_file_name;
ifstream fileExist(target_file_name);
if (fileExist)
{
int count = 0;
int contextSize = 1000;
int keySize = 1000;
char *contextFile;
char *keyFile;
contextFile = new char[contextSize];
keyFile = new char[keySize];
string command;
fileExist >> contextFile[count];
while (!fileExist.fail())
{
count++;
fileExist >> contextFile[count];
}
cout << "printing individual: " << contextFile[0] << contextFile[1];
cout << "Printing the contextfile array: " << endl;
for (int i = 0; i < count; i++)
{
cout << contextFile[count];
}

当我单独打印时,我得到 hi,这是正确的输出。

当我通过 for 循环打印时,我直接得到 ================

为什么会有差异?

最佳答案

因为你打印

cout << contextFile[count];

一遍又一遍,而不是

cout << contextFile[i];

在你的循环中,导致未定义的行为,因为 contextFile[count] 从未被初始化。

关于c++ - 我想我没有完全理解指针,但为什么这里的输出有所不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42382149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com