C ++指针数组 [英] C++ Pointer Arrays
问题描述
code
#include "stdafx.h"
#include <iostream>
void someFunc(double* pDoubleArray, int length)
{
double* pNewDoubleArray = new double[length];
for(int i = 0; i < length; i++)
{
pNewDoubleArray[i] = i * 3 + 2;
}
pDoubleArray = pNewDoubleArray;
}
int main()
{
double dbls[] = { 1, 2, 3, 4, 5 };
int length = sizeof dbls / sizeof dbls[0];
std::cout << "Before..." << std::endl;
for(int i = 0; i < length; i++)
{
std::cout << dbls[i] << ", ";
}
std::cout << std::endl;
someFunc(dbls, length);
std::cout << "After..." << std::endl;
for(int i = 0; i < length; i++)
{
std::cout << dbls[i] << ", ";
}
std::cout << std::endl;
while(true){ }
return 0;
}
输出
Before...
1, 2, 3, 4, 5,
After...
1, 2, 3, 4, 5,
下面就是我想要做的事:
1.创建一个数组,并与一些值填充它
2.传递数组指针的函数,将创建一个新的阵列,并重新分配中传递到新创建的阵列之一
3.打印出来的变化
Here's what I am trying to do: 1. Create an array and fill it with some values 2. Pass that array as a pointer to a function that will create a new array and reassign the one that was passed in to the newly created array 3. Print out the changes
我没有看到任何改变,虽然,我不知道为什么。
I am not seeing any changes though, and I do not know why.
推荐答案
你的函数someFunc的接口是错误的。它应该需要一个指针的地址的引用(或指针的指针),这样就可以返回新的数组的地址。否则,你只是修改本地值。
The interface of your function someFunc is wrong. It should require the reference of a pointer's address (or the pointer to a pointer) so that you can return the address of your new array. Otherwise, you are simply modifying a local value.
void someFunc(double*& pDoubleArray, int length)
{
double* pNewDoubleArray = new double[length];
for(int i = 0; i < length; i++)
{
pNewDoubleArray[i] = i * 3 + 2;
}
pDoubleArray = pNewDoubleArray;
}
您呼叫的主要功能则应该通过它可以修改的值:
Your calling main function should then pass a value which can be modified:
int main()
{
double dbls[] = { 1, 2, 3, 4, 5 };
double* pArray = dbls;
// ...
someFunc(pArray, length);
// ...
for(int i = 0; i < length; i++)
{
std::cout << pArray[i] << ", ";
}
// ...
}
这篇关于C ++指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!