在堆上存储整数数组并通过指针访问它们

时间:2013-12-05 11:04:09

标签: c++ arrays pointers heap

我希望有人可以了解指针错误的地方..我读过无数的网页并试过各种各样的东西,但由于某种原因,我的代码正在返回乱码(我猜可能是内存地址而不是我的数组中的数据)。该程序的目的是在堆上创建一个包含100个元素的数组,通过指向函数的指针传递该数组(以及两个整数变量start和end);将在堆上创建一个新数组(这包含使用开始和结束变量的原始数组的一个块),并将指向此数组的指针传递回main方法,以便可以输出新数组。我的问题不仅是输出看起来是位置而不是值,而且似乎100输出的值不是预期的20。我花了好几个小时试图找出出错的地方,当我认为我理解指针的概念时,我的信仰被红色的波浪形和不正确的输出所摧毁。请帮忙!我的代码如下:

#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;

double* getSubArray(double*, int, int);// Declare a function that will get the sub array

int _tmain(int argc, _TCHAR* argv[])
{
    const int size = 100;// Declare the size of the array
    double* pA;// Declare the variable to hold the pointers to the data in array
    double* pB;

    int start = 15;
    int end = 35;

    pA = new double[size];// Create space for the array
    srand(clock());// Seed the program to the computers current time so that random gets a different set of random numbers everytime it is run

// Use a for loop to traverse through each element of the array (starting at index 0) placing a number defined by the random function that is no higher than 250
    for (int i = 0; i < size; i++)
    {
        pA[i] = rand()%250;
    }

cout << "An Array of 100 numbers is created and stored in the heap, these values are:" << endl;
// Output the Array for the user to see
for (int j = 0; j < size; j++)
{
    // Place 10 numbers on each line
    if (j % 10 == 0)
    {
        cout << endl;
    }
    cout << *(pA + j) << " ";
}

cout << endl << "The program will build a second array using the data between the indexes " << start << " & " << end << endl;

pB = getSubArray(pA, start, end);// Pass the data to the method

// Output second array for user to compare
for (int k = 0; k < size; k++)
{
    // Place 10 numbers on each line
    if (k % 10 == 0)
    {
        cout << endl;
    }
    cout << *(pB + k) << " ";
}

system("pause");


return 0;
}

double* getSubArray(double* pA, int start, int end)
{
    double* pB = new double[end-start];// Declare space in the heap for the new array whoes size is the size of the criteria given

for (int i = 0; i < (end - start); i++)
{
    for (int j = start; j < end; j++)
    {
        *(pB + 0) = pA[j];
    }
}
return pB;
}

1 个答案:

答案 0 :(得分:1)

*(pB + 0) = pA[j];

继续写入数组的第一个元素。当然你想依次写每个元素:

for (int i = start; i < end; ++i) {
    pB[i-start] = pA[i];
}

或者如果您不想编写自己的循环

std::copy(pA+start, pA+end, pB);

不要忘记delete[] new[]所有内容,或者为了省去低级别内存管理,请使用std::vector为您管理动态数组。