Pointer to a Vector of Vectors in a Function Gives 'expression must have pointer type' error

Viewed 116

Visual Studio Code gives me an 'expression must have pointer type' error for the line int size = graph->at(node)->size();. I am aware that I could use references but I want to know how to do it with a pointer.

#include <vector>
using namespace std;
void getPathEdges(vector<vector<int>>* graph, int sink, int count, int node, vector<int>* path) {
    if (node == sink) {
        path->push_back(count);
    }
    else {
        count++;
        int size = graph->at(node)->size();
        for (int i=0; i<size; i++) {
            getPathEdges(graph, sink, count, i, path);
        }
    }
}
3 Answers

You're going to want

graph->at(node).size();

The first access is a -> because you have a vector<vector<int>>* (a pointer). graph->at(node) returns a vector<int> (not a pointer), so access on it is done simply via ., not ->.

You need to think about what your pointer actually points to. If we take away the * from the vector<vector<int>>* graph declaration, then we are left with this: a vector of vectors.

So, when you have dereferenced the pointer once (in graph->at()), then you are left with just a vector (not a pointer to the vector). (The -> dereferences the pointer and the at() call returns the relevant inner vector.)

So, just replace the second -> in that line with a simple . operator:

#include <vector>
using namespace std;
void getPathEdges(vector<vector<int>>* graph, int sink, int count, int node, vector<int>* path)
{
    if (node == sink) {
        path->push_back(count);
    }
    else {
        count++;
        int size = graph->at(node).size(); // Only dereference ONCE!
        for (int i = 0; i < size; i++) {
            getPathEdges(graph, sink, count, i, path);
        }
    }
}

The issue was that graph->at(node) didn't return a pointer, so using ->size() on it was invalid. Change int size = graph->at(node)->size(); to int size = graph->at(node).size();.

Related