gpt4 book ai didi

c++ - 如何删除在函数中创建的动态数组

转载 作者:太空宇宙 更新时间:2023-11-04 15:11:39 24 4
gpt4 key购买 nike

我必须编写一个程序(不使用 vector ,也不使用结构或 OOP)来计算两个多项式的和与乘积。这是我的代码:

//Task 4.19 & 4.20
#include <iostream>
#include <cmath>
double* definePoly(char& symbol, char& coef, int& k)
{
std::cout << "deg(" << symbol << "(x)) = ";
std::cin >> k;
symbol++;
double* a = new double[k];
for (int i = k; i >= 0; i--)
{
std::cout << coef << "_{" << i << "} = ";
std::cin >> a[i];
}
coef++;
return a;
}
void printPoly(int n, double* P, char& symbol)
{
symbol--;
std::cout << symbol << "(x)=";
for (int i = n; i >= 0; i--)
{
if (P[i] != 0)
{
if (P[i] > 0)
{
std::cout << '+';
}
std::cout.setf(std::ios::fixed);
std::cout.precision(2);
std::cout << P[i] << ".x^{" << i << "}";
}
}
std::cout << "\n";
symbol++;
}
double* sumPoly(double* a, int n, double* b, int m, char& symbol)
{ // Task 4.19
symbol++;
double* c = new double[(n + m + abs(n - m)) / 2];
if (n > m)
{
for (int i = 0; i <= m; i++) c[i] = a[i] + b[i];
for (int i = m + 1; i <= n; i++) c[i] = a[i];
}
else if (n < m)
{
for (int i = 0; i <= n; i++) c[i] = a[i] + b[i];
for (int i = n + 1; i <= m; i++) c[i] = b[i];
}
else for (int i = 0; i <= n; i++)c[i] = a[i] + b[i];
return c;
}
double* prodPoly(double* a, int n, double* b, int m, char& symbol)
{ // Task 4.20
symbol++;
double* d = new double[n + m];
for (int p = 0; p <= n + m; p++)
{
d[p] = 0;
for (int i = 0; i <= n; i++)
for (int j = 0; j <= m; j++)
if (i + j == p) d[p] = d[p] + a[i] * b[j];
}
return d;
}
int main()
{
int n, m;
char symbol('P'), coef('a');

double* firstPoly = definePoly(symbol, coef, n);
printPoly(n, firstPoly, symbol);

double* secondPoly = definePoly(symbol, coef, m);
printPoly(m, secondPoly, symbol);

double* sum = sumPoly(firstPoly, n, secondPoly, m, symbol);
std::cout << "Sum:\n";
printPoly((n + m + abs(n - m)) / 2, sum, symbol);

double* prod = prodPoly(firstPoly, n, secondPoly, m, symbol);
std::cout << "Product:\n";
printPoly(n + m, prod, symbol);

/*delete[] firstPoly;
delete[] secondPoly;
delete[] sum;
delete[] prod;*/

return 0;
}

完美,但当我取消注释删除时,visual studio 告诉我有错误,否则有泄漏。

如何删除/释放内存来解决这个问题?

最佳答案

double* a = new double[k];
for (int i = k;
std::cin >> a[i];

k 元素数组的最后一个元素的索引是 k - 1 您在所有循环中越界访问数组(这只是其中一个他们) 。程序的行为未定义。

how can i delete dynamic array created in a function

就像您要删除在函数外部创建的动态数组一样,就像您尝试删除它一样:

delete[] firstPoly; // etc

但是您必须确保您的程序不会因未定义的行为而破坏其自身的内存。

关于c++ - 如何删除在函数中创建的动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57252837/

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