Home > Back-end >  Vector Pointer in C
Vector Pointer in C

Time:10-06

I have a vector storing struct, and I pass it by address to a function. I wonder why I can only access to the elements by writing

(*v)[0].value

instead of

v[0].value

When I use struct array, and pass it to a function by address, I can simply write

v[0].value to get the value of an element. Any explanation is welcomed and thanks in advance.

CodePudding user response:

You're comparing a pointer to the first element of an array to a pointer to the whole vector.

Let's try to make a pointer to the whole array instead of its first element:

int a[3] = {1,2,3};
int (*ap)[3] = &a;
// int v1 = ap[0]; // error
int v2 = (*ap)[0]; // ok

Which is exactly like how a pointer to a vector behaves:

std::vector<int> b = {1,2,3};
std::vector<int> *bp = &b;
// int v3 = bp[0]; // error
int v4 = (*bp)[0]; // ok

Or, the other way around, let's make a pointer to the first element of a vector:

std::vector<int> c = {1,2,3};
int *cp = c.data(); // or `&c[0]`
int v5 = cp[0]; // ok

Which is similar to a pointer to the first element of an array:

int d[3] = {1,2,3};
int *dp = d; // or `&d[0]`
int v6 = dp[0]; // ok

CodePudding user response:

Suppose the struct that you have is named yourtype.

Case 1

The type of the expression (*v)[0] is yourtype which has a member called value so we're allowed to write (*v)[0].value.

Case 2

In this case, the type of the expression v[0] is vector<yourtype> and since vector<yourtype> doesn't have any member called value, we're not allowed to write v[0].value and we will get an error here saying exactly this:

error: ‘class std::vector’ has no member named ‘value’

Also, you should pass the vector by reference instead of a pointer to that vector. This is one of the reason why C has pass by reference(unlike C) so that you don't have to dereference things everywhere.

  • Related