gpt4 book ai didi

c++ - 处理数组队列

转载 作者:太空宇宙 更新时间:2023-11-04 15:48:39 25 4
gpt4 key购买 nike

#ifndef UNICODE
#define UNICODE
#endif

#include <iostream>
#include <Windows.h>
#include <queue>

using namespace std;

void addSomeContent(queue<TCHAR*> &s)
{
static int counter=0;
TCHAR buffer[30];

wsprintf(buffer,TEXT("foo%d"),counter);

s.push(buffer);
counter++;

if(counter < 10)
addSomeContent(s);
}


int main (void)
{
queue<TCHAR*> strings;

addSomeContent(strings);

while(!strings.empty())
{
wcout<<strings.front()<<endl;
strings.pop();
}

system("pause");
return (0);
}

输出:

foo0

期望:

foo0
foo1
.
.
.
foo9

我哪里错了?

最佳答案

原因是您的 buffer 是堆栈上的本地变量。一旦您离开该功能,它就会过期。

如果你真的想这样做,在堆上创建它 TCHAR *buffer = new TCHAR[30];。您可能需要在某个时间点后删除[]它。

但是,我认为使用一些内置类型或 STL 容器而不是操作指针将使您的代码更具可读性和可管理性。

关于c++ - 处理数组队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12520232/

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