Role of parentheses in an array of pointers in C ++

While trying to implement plots using this link I ran into a serious syntax doubt.

/ 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;
};

      

In the above, it is implemented in C, whereas I have implemented it in C ++. And now the function to create the chart data structure:

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;
}

      

This code gives an error: array denied is not allowed after nested type id. If I just remove paranthese from the problem row, everything works fine. Why is this happening?

EDIT:

I know how to fix this problem. You just need to do it.

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

      

Question: WHY is it wrong?

+3


source to share


2 answers


There are two general choices new

that allow you to copy between a keyword and a type. The objects enclosed within are included as arguments to the function operator new

. They are useful

  • To manually specify memory instead of using the operator new

    default function .
  • To indicate non-throwing behavior. This is handy if you don't want the new expression to std::bad_alloc

    fetch when the freestore allocation fails.

1.posting new

char* ptr = new char[sizeof(T)];   // allocate memory
T* tptr = new(ptr) T;              // construct in allocated storage ("place")
tptr->~T();                        // destruct

      

2.nothrow

auto p* = new (std::nothrow) char;

      

It won't throw, but it will crash when set p

to nullptr

.



Question: WHY is it wrong?

Because it is not part of the legal grammar where the parenthesis can occur; an error array bound forbidden after parenthesized type-id

means that the compiler thinks you did it

T *arr = new (T) [count];

      

which is not correct since for an array you are doing

T *arr = new T[count];

      

i.e. type without parentheses. Here, as juanchopanza mentioned in the comments, type T[]

, so you can do T *arr = new (T[count]);

.

+1


source


"The question is: WHY is it wrong? "

The chapter 5.3.4 of the C ++ language specification shows quite clearly that parentheses, implicitly following a keyword new

, place new expressions:



enter image description here

+2


source







All Articles