-6
#include<iostream>
#include <cstring>
using namespace std;  
typedef struct {char *str;}String;
int main(){
    String name,add;
    cout<<"Name: ";
    cin>>name.str;
    cout<<"\n\tadd: ";
    cin>>add.str;
    cout<<"\n\tName:"<<name.str;
    cout<<"\n\t Add:"<<add.str;
    return 0;
}

Input is successful and then the program crashes.
Error displayed: stopped working

Mat
  • 202,337
  • 40
  • 393
  • 406
  • 3
    You should get [a couple of good books to read](https://stackoverflow.com/a/388282/440558). And learn about pointers. They don't just "magically" point somewhere valid, you have to *make* them point somewhere. – Some programmer dude Jan 31 '18 at 16:27
  • 2
    When you attached your debugger to it, and stepped through it line by line, where did it fail? – UKMonkey Jan 31 '18 at 16:27
  • `str` points to some semi-random location, `std::cout` tries to write to that location, your operating system sees a rogue program trying to write to memory that doesn't belong to it and kills it. – nwp Jan 31 '18 at 16:29

2 Answers2

4

No, no, no, just use std::string! Easier to use, and easier to understand!

#include<iostream>
#include <string>
using namespace std;  

int main(){
    string name,add;
    cout<<"Name: ";
    getline(cin, name); // A name probably has more than 1 word
    cout<<"\n\tadd: ";
    cin>>add;
    cout<<"\n\tName:"<<name;
    cout<<"\n\t Add:"<<add;
    return 0;
}

As far as your problem goes with your original code, it is that you haven't allocated any memory for your char*, and are reading into memory that isn't yours.

Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
  • my bad I used to code in turboc++ in the past because of outdated college and all and turboc++ didn't have anything like string. so thanks or putting some light on this – Sahil Yadav Feb 02 '18 at 16:20
2

str is a member of structure and its of pointer type and while doing name.str; it doesn't have any valid memory thats why it crashes at run time.

First allocate memory for str as

name.str = new char [SIZE]; /* SIZE is the no of bytes you want to allocate */

Once work is done free the memory by using delete to avoid memory leakage.

delete [] name.str;
Achal
  • 11,821
  • 2
  • 15
  • 37