Smiled_One
Smiled_One

Reputation: 465

C++ cout string print its memory value

I am trying to create a keygen to some reversing challenges around there. I decided to try to code it in a language that I don't know well, c++

I not sure how to use pointers yet, but I thing that I implemented the algorithm well without them. the only problem is that I print the answer I get it's memory location instead all the string.

char decrypt(char c, int position);
int main(){

    cout << "Enter username:" << endl;
    string username;
    string answer[20] = "";
    cin >> username;
    for (int i = username.length(); i > 0; i--){
        answer[username.length() - i] = decrypt(username[i-1],i);
        if (i == 0){
            answer[username.length() +1] = '\0';
        }
    }
    return 0;
}
char decrypt(char c, int position)
{
    if (position == 4){
         return '-'; }
    if (c > 'M'){
        c -= 17;    }
    else{
        c += 21;    }
    c ^= position;
    c ^= 2;
    return c;
}

If I will try to print the string username I will get the string and not the memory location of username. So I'm not sure what is going on.. Thanks for any help, Or

Upvotes: 3

Views: 987

Answers (3)

creichen
creichen

Reputation: 1768

In this code, answer is not a string – it is an array of 20 strings. You probably want char answer[20], or, more likely, to create a single string answer and append the result with answer += character.

Upvotes: 2

S.Clem
S.Clem

Reputation: 521

First, try to use the answer variable as a string and not a char*. A string authomatically resize and realocates its internal buffer if needed.

The code could looks like this:

string username;
string answer;
cin >> username;
for (int i = 0; i < username.length(); i++)
{
    answer += decrypt(username[i],i+1);
}

Then if you want to see the content of the internal string buffer, you can use answer.c_str ();

Edit:

As songyuanyao said, your code uses an array of string. But the solution of using an array of 20 chars (char answer [20]) leads to a memory issue if the username has a size of 20 or more.

Upvotes: 3

songyuanyao
songyuanyao

Reputation: 172884

If I understand your question correctly,

string answer[20] = "";

should be

char answer[20];

string answer[20] is array of std::string, not the c-style string (i.e. char[]).

Upvotes: 3

Related Questions