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

Declaring a char pointer

I’m trying to make a login/register project and I have difficulties in declaring the char* tempUsername from this code (SIGSEVG segmentation fault)

char *tempUsername, *tempPassword, *tempPasswordConfirm, *tempSecurityQuestion;

/*
no other declaration for tempUsername here
*/

std::cout<<"Enter your new username:\n";
std::cin>>tempUsername;

//process stops here

        if(fileSearch(newFilename(tempUsername))) {
            std::cout<<"Username already exists! Choose another username!\n";
        }
        else {
            std::cout<<"Enter your password:\n";
            std::cin>>tempPassword;
            std::cout<<"Confirm your password:\n";

I’m having a hard time understanding anything about pointers, so any advice is more than helpful!

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

>Solution :

char *tempUsername
std::cin>>tempUsername;

The problem here is that your pointer is uninitialised. When you try to extract from the input stream into the uninitialised pointer, the behaviour of the program will be undefined. Don’t do this.

Your goal seems to be to read a string of user input. A solution that I can recommend is to use the std::string class:

std::string tempUsername;
std::cin >> tempUsername;

No need to use a pointer to achieve this.

I can use a char* as an array of chars, is that true?

It is not true in general. If you have a char* that points to an element of an array of char, then you can use that char* as an iterator to access the elements of the array.

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