|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
C++ Pointers and Strings
Help!
What happens if I have the following code? PHP Code:
If my knowledge of C++ pointers, and how they work are correct, that code assigns the address of the first character of "Hello" to the pointer. Then, the next line, takes a string from the user, and assigns the address of the first character of that string to the pointer? Right? |
|
#2
|
|||
|
|||
|
I don't think you can use a char* for cin, can you?
|
|
#3
|
|||
|
|||
|
You can't? Hmm
![]() |
|
#4
|
||||
|
||||
|
Why don't you use std::string?
__________________
Jon Sagara "Me fail English? That's unpossible!" |
|
#5
|
|||
|
|||
|
This may be too much information
This should clear up how to use c strings and c++ strings
Code:
#include <iostream>
#include <string>
int main(){
char * astring; //how you declare c strings
astring = new char[strlen("Hello")+1]; // you must set the size plus the null byte '\0'
strcpy(astring, "Hello"); // how things are copied into a c string
cout << astring << endl; // Hello
delete [] astring; // If you new you must delete; however delete comes first
astring = new char[30]; // Test this by typing in way more then 30 characters
cin >> astring;
cout << astring << endl;
}
/*
int main(){
//With strings, it is much easier b/c you don't worry about memory
// The trade off is speed; however, it is best to use strings anyway
// Make sure you #include <string>
string astring = "Hello";
cout << astring << endl;
cin >> astring;
cout << astring << endl;
//If you look at the new char[30], you witness a buffer overflow
// Hackers will type in more characters then allowed to change other parameters
// This is why I use strings!
}
*/
|
![]() |
| Viewing: Dev Shed Forums > Programming Languages > C Programming > C++ Pointers and Strings |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|