错误:“calloc”未在此范围内声明

error: ‘calloc’ was not declared in this scope

本文关键字:范围内 声明 calloc 错误      更新时间:2023-10-16

我正在使用g++编译我的代码arch linux

编译时收到此错误。 .error: ‘calloc’ was not declared in this scope

我没有尝试用ubuntu编译这段代码,但我很确定它会通过。那么这是与arch linux有关的问题还是我的代码出了问题

这是我的代码:

#include <cstdio>
using namespace std;
class Graph
{
    private :
    unsigned int numNodes;
    class Connection
    {
        public :
        int to;
        int weight;
        Connection (int to,int weight)
        {
            this->to = to;
            this->weight = weight;
        }
        Connection (int to)
        {
            this->to = to;
        }

    };
    Connection **nodeList;
    public :
    Graph (unsigned int numNodes)
    {
        this->nodeList = calloc (sizeof (Connection*),numNodes);
        this->numNodes = numNodes;
    }   
};

std::calloc函数在<cstdlib>中定义。您需要包含它才能修复此错误。

话虽如此,您最好使用 operator new - 一种在C++中分配动态内存的惯用方法。

而且使用std::vector而不是使用原始指针和new会更好(更好)。