首页 > 解决方案 > 指针数组的分段错误

问题描述

尝试为我的指针数组输入数据时出现段错误。我对编码很陌生,所以任何帮助都会很棒。我的任务是制作一个指针数组,然后显示,交换它们,然后对它们进行排序

#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;
}

标签: c++arrayspointerssegmentation-fault

解决方案


您只为外部数组分配了空间,但您还需要为每个内部浮点数分配空间。

所以在调用此行之前:

cin >> *speed[i];

您需要先为其分配空间:

speed[i] = new float;

推荐阅读