I am trying to make the first part below function correctly:
How do I input a char pointer string?Code:char *test;
cin >> test; // This does not work
char test2[25];
cin >> test2; // This seems to work
Printable View
I am trying to make the first part below function correctly:
How do I input a char pointer string?Code:char *test;
cin >> test; // This does not work
char test2[25];
cin >> test2; // This seems to work
As you admitted, it's a pointer. You must first point it to some memory.
Try this:
Code:char *test;
test = new char[25];
cin >> test; // Now this does work
Okay, I thought since I could assign:
then I could input the same string. I thought there was a way to do this directly.Code:char *test = "Hello";
Is this the only way to do it?
Code:char *test = new test[25];
delete test;
To my knowledge, which may be wrong, that is how you use a cstring, with this slight modification:
Code:char *test = new char[25]; // Use new char not new test
...
delete test;
No.
Everything in quotes gets placed in a special location in the executable that the compiler produces. This could be in some string table in the .data segment (or some equivalent).
test in this case is simply a pointer, and it's given the address of where "Hello" was stored in this special location.
When you use cin to read in a string and give it a pointer, the pointer in your example is pointing nowhere meaningful, and is most likely pointing to invalid memory. Such an attempt to store a string where it points to is undefined, which means the system is not guarenteed to do anything in particular. It is allowed to do whatever it wants. On many modern systems, you can probably expect such an attempt to result in a crash.
For simple buffers, you may not need dynamic memory, and you can do well enough with a simple array. The above code will work just as fine, provided you only use test after you allocate a valid block of memory for it, and before you deallocate said block of valid memory.
"Hello" is a const char*. It is only for backwards compatibility that you are allowed to assign it to a char*. However, you still aren't allowed to modify it even if you assign it to a char*.Code:char* test = "Hello";
You have to use delete [] if you used new [].Code:char *test = new char[25];
delete [] test;
Of course, in C++ you should be using the C++ string class instead of C style strings (null terminated character arrays). And if you need a dynamic array, you would use vector instead of new[]/delete[].