gpt4 book ai didi

c++ - 在函数内修改数组指针

转载 作者:行者123 更新时间:2023-11-30 01:56:30 30 4
gpt4 key购买 nike

    void nothing(int* buffer)
{
int* temp = new int[5];
for (int i = 0; i < 5; i++)
{
temp[i] = i;
}
buffer = temp;
}

void main(int argc, char* argv[])
{
int* a = new int;
nothing(a);
for (int i = 0; i < 5; i++)
{
cout << a[i] << endl;
}
system("pause");
}

为什么我不能从缓冲区中获取新地址?我正在尝试将一个数组(指针)传递给函数并在内部对其进行修改。

输出:

 -842150451
-33686019
-1414812757
-1414812757
0

预期:

0
1
2
3
4

最佳答案

您需要将指针传递给指针(或者正如其他人指出的对指针的引用),即 int ** 然后使用 *buffer = temp 和使用 nothing(&a) 调用函数。

如果您不这样做,您对缓冲区变量所做的更改将在您离开该函数时丢失。将指针变量本身想象成任何数字,因为它指向的东西在函数结束后仍然存在。

但是,我建议您改用 std::vector:

void nothing(std::vector<int> &buffer) {
...
}

int main(int argc, char* argv[])
{
std::vector<int> a;
nothing(a);
for (int i = 0; i < 5; i++)
{
cout << a[i] << endl;
}
system("pause");
return 0;
}

根据您的场景,您甚至可能希望将 nothing 函数更改为初始化样式函数,即直接返回一个对象:

std::vector<int> nothing() {
std::vector<int> temp;
// fill vector here
return temp;
}

int main(int argc, char* argv[])
{
auto a = nothing();
for (int i = 0; i < 5; i++)
{
cout << a[i] << endl;
}
system("pause");
return 0;
}

这更像 C++,使您不必手动删除数组。

要实际将数据生成到 vector 中,请查看 Initialization of std::vector<unsigned int> with a list of consecutive unsigned integers.

关于c++ - 在函数内修改数组指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19735121/

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