gpt4 book ai didi

c++ - C++中括号在指针数组中的作用

转载 作者:太空狗 更新时间:2023-10-29 21:19:21 27 4
gpt4 key购买 nike

尝试使用 this 实现图形链接,我遇到了严重的语法疑问。

/ A structure to represent an adjacency list node
struct AdjListNode
{
int dest;
struct AdjListNode* next;
};

// A structure to represent an adjacency liat
struct AdjList
{
struct AdjListNode *head; // pointer to head node of list
};

// A structure to represent a graph. A graph is an array of adjacency lists.
// Size of array will be V (number of vertices in graph)
struct Graph
{
int V;
struct AdjList* array;
};

在我上面提到的,它是用 C 实现的,而我用 C++ 实现了它。现在是创建图形数据结构的函数:

struct Graph* createGraph(int V) {
struct Graph *graph;
graph = new (struct Graph);
graph->V = V;

//the problem line below
graph->array = new (struct AdjList)[V];
//initialize all the elements in the array as NULL
for(int i = 0; i < V ; i++) {
graph->array[i].head = NULL;
}
return graph;
}

此代码给出错误:array bound forbidden after parenthesized type-id而如果我只是从问题行中删除 paranthese,一切正常。为什么会这样?

编辑:

我知道如何解决这个问题。只需要这样做。

graph->array = new struct AdjList[V];

问题是为什么它不正确?

最佳答案

"The question is WHY is it incorrect?"

c++ language specification的第5.3.4章, 非常清楚地表明紧跟在 new 关键字之后的括号是为 placement new 表达式保留的:

enter image description here

关于c++ - C++中括号在指针数组中的作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27636018/

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