为什么“删除”操作员给我访问权限违规

问题描述 投票:-1回答:1
#include <iostream>

using namespace std;

int *res=new int[0];

int res_size;

void multiply(int y);

void factorial(int x)

{

    res[0]=1;
    res_size=1;
    for (int i=2;i<=x;i++)
        multiply(i);
    for (int i=res_size-1;i>=0;i--)
        cout << res[i];
}

void multiply(int y)

{

    static int prod=1;
    int carry=0;
    for (int i=0;i<res_size;i++)
    {
        prod=res[i]*y+(carry);
        res[i]=prod%10;
        carry=prod/10;
    }
    while (carry)
    {
        res[res_size]=carry%10;
        carry=carry/10;
        res_size++;
    }
}

int main()

{

    int n;
    cout << "Enter a number" << endl;
    cin >> n;
    factorial(n);
    delete[] res;
    return 0;
}

[当我使用delete []运算符时为什么会得到

Access violation reading location at address
c++ dynamic-memory-allocation delete-operator
1个回答
2
投票

您为数组分配了零个元素

int *res=new int[0];

您可能无法像这样写一个数组

res[0]=1;

程序具有未定义的行为。

您可以使用类模板std::vector代替动态分配的数组。在这种情况下,您可以使用方法push_back将元素添加到向量中。

© www.soinside.com 2019 - 2024. All rights reserved.