char* string

Hello again!

I've been studying but I don´t understand few things, hope you could help me..

1. Let´s say I want the user to enter a name :
How do I save that name in a char* ? (like using pointers)

1
2
char* name;
cin >> name  


2. If I have a function like this one:
1
2
3
 void thing(*char name){

}

And now, I call that function:
1
2
 thing("Hello");

Is that ok? I mean, sending " Hello".



3. And the last one, how do I initialize char* name, to hold the following "Tacos tacos"?




Thanks!
Last edited on
pointers are not strings. They're pointers. You have to make your pointer actually point to something before you can put string data there. As it is now, your pointer points to random memory and therefore you are attempting to write string data to random memory (BAD -- might cause program to crash or other weird behavior)

I just made a big old post about this here:

http://www.cplusplus.com/forum/beginner/108879/#msg592405




But really... you should avoid char pointers/char arrays anyway and just use strings. They're easier/safer.

1
2
3
4
5
6
7
8
9
std::string name;
cin >> name;

//...

void thing(std::string name)
{
  //...
}
@jmyrrie
1. Let´s say I want the user to enter a name :
How do I save that name in a char* ? (like using pointers)

1
2
 char* name;
cin >> name  



You will get abnormal termination of the program because you did not allocate memory where you are going to read a character array.

@jmyrrie
2. If I have a function like this one:

1
2
3
  void thing(*char name){

}


And now, I call that function:

thing("Hello");

Is that ok? I mean, sending " Hello".


You will get a compilation error because this declaration of the parameter
*char name is invalid. The correct declaration of the parameter will look the following way

1
2
3
4
5
6
7
8
  void thing( const char *name){

}

int main()
{
   thing("Hello");
}


@jmyrrie
3. And the last one, how do I initialize char* name, to hold the following "Tacos tacos"?


const char *name = "Tacos tacos";

or

const char *name = { "Tacos tacos" };

or

const char *name { "Tacos tacos" };

or

const char *name( "Tacos tacos" );

Last edited on
Ok, but whats the difference beetwen const char *name and char* name?
Also, Can I do this:

1
2
3
4
                    const char* p;
                    cin >>p;

        

If not, how can I do it?
jmyrrie wrote:
Ok, but whats the difference beetwen const char *name and char* name?
The first is a non-const pointer to const character. The second is a non-const pointer to non-const character.
jmyrrie wrote:
Also, Can I do this:

1
2
3
4
                    const char* p;
                    cin >>p;

        

If not, how can I do it?
Did you read Disch's post at all? ;)
No, I didn't
I will :D
But thanks!!!



-------------------
amazing info!
Last edited on
Topic archived. No new replies allowed.