Problem with pointers to a string

May 27, 2011 at 5:07pm
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

#include <iostream>
#include <string>
using namespace std;

string getLetterAt(string*, int);

int main()
{
    cout<<getLetterAt("Banana",3)<<endl;//what's wrong with this line?
    return 0;
}

string getLetterAt(string* word, int letter)
{
    for(int i=0; i<letter;i++)
    {
        word++;
    }
    return *(word);
}


May 27, 2011 at 5:13pm
Instead, how about:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
using namespace std;

string getLetterAt(string*, int);

int main()
{
    string s("Banana");
    cout << s[3] << endl;
    return 0;
}
Last edited on May 27, 2011 at 5:13pm
May 27, 2011 at 5:14pm
What is this supposed to do? When you increment 'word', you move one std::string over in memory, pointing to random garbage. If you want a character use .at() or the array subscript operator [] on the string.

The other problem with the call is that you take a string*, but you are passing a char* which is only convertible to string, not string*.
May 27, 2011 at 5:14pm
I specifically want to do it using pointers, because i'm not very good at them.
Thanks for the help, though :)
May 27, 2011 at 5:25pm
Then you are using the wrong pointer. Besides, you code shouldn't even compile because you are passing a const char* when getLetterAt() expects a string*.

Therefore, change the function to const char* getLetterAt(const char *word, int letter) and you should be good to go. Oh, and don't return *(word), just return word.
May 27, 2011 at 5:26pm
In that case I'd use a char*. A string* be useful here except to provide meaningless indirection.
May 27, 2011 at 5:30pm
Thanks. That worked. One question, why do we make char * const?
May 27, 2011 at 5:36pm
All string literals in the source code, like "Banana" over there occupy memory, but you did not allocate that and therefore you are not considered to be the owner of it. Therefore you cannot change it. This is why it is const(ant).

Since you are returning a pointer to the 3rd character, that is still read-only memory for you, so you also need to return const char*.
Topic archived. No new replies allowed.