Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

const char* pointer handling (C++)

Hi everyone I have a simple task in C++:

-> writing a program that takes a string from user input and loops over the characters in the string via a pointer.

If I understand correctly, then a previously declared string name; variable can also be accessed via const char*, implying that I can declare a pointer in the following manner: const char *pName = &(name[0]);. When printing the pointer, however, not the memory address but the actual variable is displayed in the terminal (see my code below). This prevents me from incrementing the pointer (see for loop).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Filename: countchar.cpp

#include <iostream> 
using namespace std;

int main() {
    string name; 

    std::cout << "Provide a string." << endl;
    std::cin >> name;

    const char *pName = &(name[0]);
   

    cout << pName << endl;

    // further downstram implementation
    // int len = name.length();
    // for(int ii = 0; ii < len; ii++){
    //     std::cout << "iteration" << ii << "address" << pName << endl;
    //     std::cout << "Character:" << *pName << endl;
    //     (pName+1);
    // }

    return 0;
}

Terminal output:

$ g++ countchar.cpp -o count
$ ./count
$ Provide a string.
$ Test
$ Test 

As I am a quite a noob in regard to C++ help and an explanation are both highly appreciated (No material found online that solves my problem). Thanks in advance!

>Solution :

The operator << overloaded for a pointer of the type char * such a way that it outputs the string pointed to by the pointer.

So according to the assignment instead of these statements

const char *pName = &(name[0]);


cout << pName << endl;

you need to use a loop like

for ( const char *pName = &name[0]; *pName != '\0'; ++pName )
{
    std::cout << *pName;
}
std::cout << '\n';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading