我希望有人可以阐明我在哪里出错了指针。.我读了无数的网页并尝试了各种尝试,但是由于某种原因,我的代码返回了乱码(我猜这可能是内存地址)而不是数组中的数据)。该程序的目的是在堆上创建一个包含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;
}
*(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
来为您管理动态阵列。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句