gpt4 book ai didi

c++ - 段错误错误 11 C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:01:19 25 4
gpt4 key购买 nike

所以我在代码的开头遇到了段错误。我试过在不同的点运行一些测试,错误似乎是在我为数组分配内存时。我刚刚开始学习堆和堆栈内存,所以我不确定我是否在那里做错了什么。任何帮助将不胜感激。

#include <iostream>
using namespace std;

//Function Prototypes
void sort(int A[], int n);
int findMin(int A[], int n, int j);
int swap(int& a, int& b);
double median(int A[], int n);
void output1(int median);
void output2(double median);

int main()
{
int size;
int array[size]; //Segmentaion fault here
int i = 0;

cout << "Enter the size of the list (< 1 to quit): ";
cin >> size;

while(size >= 1)
{
double element;

cout << "Enter element " << i+1 << ": ";
cin >> element;

array[i] = element;

i++;

while(i < size)
{
cout << "Enter element " << i+1 << ": ";
cin >> element;

array[i] = element;
i++;
}

sort(array, size);
median(array, size);

cout << "Enter the size of the list (< 1 to quit): ";
cin >> size;
}
delete [] array;
return 0;

}


void sort(int A[], int n)
{
int min;
for(int i = 0; i < n; i++)
{
min = findMin(A,n,i);
//min = findMinIndex(p, size, i);

//if(min )
swap(A[i],A[min]);
//swap(p[i],p[min]);
}
}

int findMin(int A[], int n, int j)
{
int minIndex = j;
for(int i = j+1; i < n; i++)
if(A[i]<A[minIndex])
minIndex = i;
return minIndex;
}

int swap(int& a, int& b)
{
int temp;
temp = a;
a = b;
b = temp;
}

void output1(int median)
{
cout << "The median is " << median << "." << endl;
}

void output2(double median)
{
cout << "The median is " << median << "." << endl;
}


double median(int A[], int n)
{


if(n % 2 == 0)
{
int div1 = n / 2;
int num1 = A[div1];
int num2 = A[div1 -1];
double median = (num1 + num2) / 2;
output2(median);
}
else
{
int div2 = n - 1;
int median = div2 / 2;
output1(median);
}
}

最佳答案

因为您没有初始化 size,所以该变量中的值实际上可以是任何值。如果它恰好太大,比如 106,840,406,那么您将无法获得该大小的 int[]

基本上,将您的 size 变量初始化为合理的值。

关于c++ - 段错误错误 11 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41729828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com