Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding strings as pointers in C++

I have troubles understanding strings as pointers. Apparently a string is understood as a pointer which points to the first address of the string. So using the "&"-operator I should receive the address of the first character of the string. Here's a small example:

#include "stdafx.h"
#include <iostream>
using namespace std;

int main(){
    char text[101]; 
    int length;
    cout << "Enter a word: ";
    cin >> text;
    length = strlen(text);
    for (int i = 0; i <= length; i++) {
        cout << " " << &text[i];
    }
    return 0;
}

When entering a word such as "Hello", the output is: "Hello ello llo lo o". Instead I expected to receive the address of each character of "Hello". When I use the cast long(&text[i]) it works out fine. But I don't understand why. Without the cast, apparently the "&"-operator gives the starting address of the string to be printed. Using a cast it gives the address of every character separately. Maybe sb. can explain this to me - I'd be really grateful!


1 Answers

&text[i] is equivalent to text + i and that shifts the pointer along the char[] array by i places using pointer arithmetic. The effect is to start the cout on the (i)th character, with the overload of << to a const char* called. That outputs all characters from the starting point up to the NUL-terminator.

text[i] however is a char type, and the overload of << to a char is called. That outputs a single character.

In C++, if you want a string, then use std::string instead. You can still write cin >> text; if text is a std::string type! Your code is also then not vulnerable to overrunning your char buffer.

like image 104
Bathsheba Avatar answered Dec 22 '25 16:12

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!