【发布时间】:2018-06-06 23:10:33
【问题描述】:
尝试为我的指针数组输入数据时出现段错误。我对编码很陌生,所以任何帮助都会很棒。我的任务是创建一个指针数组,然后显示、交换它们然后对它们进行排序
#include <iostream>
using namespace std;
float getValueFromPointer(float* thePointer)
{
return *thePointer;
}
float* getMinValue(float* a, float* b)
{
if (*a < *b)
{
return a;
}
else
{
return b;
}
}
int main()
{
int arraySize;
cout << "Enter the array size: ";
cin >> arraySize;
float** speed = new float*[arraySize]; // dynamically allocated array
for(int i = 0; i < arraySize; i++)
{
cout << "Enter a float value: ";
cin >> *speed[i];
}
// Core Requirement 2
for (int i = 0; i < arraySize; i++)
{
float value = getValueFromPointer(*speed+i);
cout << "The value of the element " << i << " is: ";
cout << value << endl;
}
//float *pointerToMin = getMinValue(&speed[0], &speed[arraySize - 1]);
//cout << *pointerToMin << endl;
delete [] speed;
speed = NULL;
return 0;
}
【问题讨论】:
-
为什么要使用指针和
new?您应该更喜欢使用std::vector<float>。你根本不需要指针;使用参考。
标签: c++ arrays pointers segmentation-fault