Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"error: request for member ‘size’ in ‘a’, which is of pointer type" but I didn't think it was a pointer

Tags:

c++

arrays

So, I thought I was trying to do something simple, but apparently not...

I wrote this function so I could extend it later and have a quick way to give the user a menu when required by going menu(mystrings):

int menu(string a[]) {
    int choice(0);
    cout << "Make a selection" << endl;
    for(int i=0; i<a.size(); i++) {
        cout << i << ") " << a[i] << endl;
    }
    cin >> choice;
    cout << endl;
    return choice;
}

But for some reason I get:

main.cpp: In function ‘int menu(std::string*)’:
main.cpp:38:12: error: request for member ‘size’ in ‘a’, which is of pointer type ‘std::string* {aka std::basic_string<char>*}’ (maybe you meant to use ‘->’ ?)
  int n = a.size();

when I try compiling. Could anyone translate that error for me and explain what -> is, thank you.

like image 694
Jamie Twells Avatar asked Apr 07 '14 20:04

Jamie Twells


1 Answers

You are passing an array of strings and trying to call size() on the array. Arrays degenerate to pointers when passed to a function, which explains your error.

The -> operator, or "arrow operator" (name I use), is just shorthand for (*obj).func(). This is useful if you have a pointer to a class object. Example:

string *s = &someotherstring;
s->size(); //instead of (*s).size(), saves keystrokes
like image 140
yizzlez Avatar answered Oct 21 '22 22:10

yizzlez