user1609974
user1609974

Reputation: 95

a simple c++ program crashes?

Write a program that asks the user to enter his or her first name and then last name, and that then constructs, stores, and displays a third string, consisting of the user’s last name followed by a comma, a space, and first name.Use char arrays and functions from the cstring header file.A sample run could look like this: Enter your first name: Flip Enter your last name: Fleming Here’s the information in a single string: Fleming, Flip

int main()
{

    char * fName,*lName,*fullName;

    fName = new char;
    cin.getline(fName,100);

    lName=new char;
    cin.getline(lName,100);

    fullName=new char[strlen(lName)+strlen(fName)+3];

    strncpy(fullName,lName,strlen(lName));

    fullName[strlen(lName)]=',';
    fullName[strlen(lName)+1]=' ';


    char* dummy=(char*)fullName[strlen(lName)+2];//making a pointer to the char after the ' ' char to start copying the first name

    strncpy(dummy,fName,strlen(fName));

    dummy[strlen(fName)+strlen(lName)+2]='\0';

    cout<<endl<<endl<<dummy<<endl;



    delete fullName;
    delete lName;
    delete fName;
    return 0;
}

why it crashes when i point to a char in the middle of the array and start copying ???

Upvotes: 0

Views: 352

Answers (2)

perreal
perreal

Reputation: 97948

The type of fullName[strlen(lName)+2] is char, to get the pointer do:

char* dummy=fullName + strlen(lName)+2;

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258608

fName = new char;

allocates a single char.

cin.getline(fName,100);

goes way beyond that.

Use std::string instead. You'll see that writing C++ code in C++ instead of C makes life a lot easier.

Upvotes: 7

Related Questions