Home > other >  Console couts a memory address instead of string
Console couts a memory address instead of string

Time:01-11

As I understand that strings can be treated like arrays, so I tried to insert each character of a string by iterating with a while loop. However the final cout pointed to a memory address, not the string I hoped it would print.

int main()
{
    int i = 0;
    int n = 2;
    char input;
    string str1[n];
    
    while(i<=n){
        cout<<"enter letter: ";
        cin>>input;
        str1[i] = input;
        i  ;
    }
    cout<<"Your word is: "<<str1;

    return 0;
}

The output was:

enter letter: a
enter letter: b
enter letter: c
Your word is: 0x7ffd505af1f0

How can I print my string at the end, instead of a pointer to a mem address?

More interestingly, when I adjusted the final line to cout str1[n] instead of str1, the console prints the next character in the alphabet from the last input!

cout<<"Your word is: "<<str1[n];

and the output is

enter letter: a
enter letter: b
enter letter: c
Your word is: d

How is this happening?

CodePudding user response:

Most likely you meant either string str1; or char str1[n]; (I suggest the first one, as the latter is a variable-length array supported only by compiler extensions, not a part of C ). string str1[n]; is an array of strings, which in generally decays to a pointer when passed around, so it happened in your case.

Should you decide to go with the std::string I suggest getting rid of i and n and rewriting it to sth like that:

    while(str1.size() < 2){
        cout<<"enter letter: ";
        cin>>input;
        str1.push_back(input);
    }

Should you decide to stick to C-style char array (char str1[n];) I suggest making n a compile time constant, i.e. by defining it the following way: constexpr int n = 5; (provided you're on C 11 or newer).

CodePudding user response:

When people say that strings are like arrays, they mean specifically "c-strings", which are just char arrays (char*, or char []). std::string is a separate C class, and is not like an array.

In your example, str1 is actually an array of std::strings, and when you print it, you're printing the pointer address.

Below is an example using both C std::string, and a C-string, to illustrate the difference. In general, when writing C , you should prefer std::string.

const int n = 2;
std::string str1; //A c   std::string, which is not like an array
char cstr1[n]; // a c-string, which is array-like

for(int i = 0; i < n;   i) {
    char input = '\0';
    cout<<"enter letter: ";
    cin>>input;
    str1.push_back(input); //Append to c   string
    cstr1[i] = input; //Add to array-like c-string
}
cout << "As C  : " << str1 << std::endl;
cout << "AS C: " << cstr1 << std::endl;
cout << "C   can convert to C-string: " << str1.c_str() << std:endl;

Added const to n, to make it valid C , since you shouldn't create arrays from non-const variables

  •  Tags:  
  • Related