c++ - 指针数组的分段错误
问题描述
尝试为我的指针数组输入数据时出现段错误。我对编码很陌生,所以任何帮助都会很棒。我的任务是制作一个指针数组,然后显示,交换它们,然后对它们进行排序
#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;
}
解决方案
您只为外部数组分配了空间,但您还需要为每个内部浮点数分配空间。
所以在调用此行之前:
cin >> *speed[i];
您需要先为其分配空间:
speed[i] = new float;
推荐阅读
- c - C中的复合文字存储持续时间
- python - 给定一个字典和一个键,“get_nth_element_of_value”返回位于给定键的列表的第 n 个元素
- node.js - 我如何在总和查询中使用strapi
- excel - 如何在excel中的数字之间添加逗号?
- node.js - 开玩笑 TypeScript 错误 axios_1.default.post.mockImplementation is not a function
- javascript - 有没有办法使用 Angular 和 SyncFusion 数据网格创建动态行编号列?
- c# - 不接受具有 (",') 等特殊字符的数据表 Json。“显示缺失)”错误
- c++ - Qt 自定义 QPushButton 不显示在布局上
- python - PyQt5 - QTabBar 中缺少关闭按钮图标
- wordpress - 密码存储在 wordpress 数据库中表 wp_users 中