Am 29.07.2011 04:50, schrieb cerr:
how do i correctly assign a string to a char*?
If i do it
char *test;
test= "BLABLA";
I get "warning: deprecated conversion from string constant to ‘char*’"
But strcpy() ot sprintf() doesn't work because there's no room
allocated yet. So do I actually need to allocate space with calloc()/
malloc()?
Thanks,
Ron
Hello Ron,
I don't feel like you understand what `test` -- the way you declared it
-- actually is. This is because you're speaking of assigning a string
to `char*`. But a variable with a type `char*` does not store strings.
It stores addresses. So, you can only assign some address to it. While
it is possible to use a string literal on the right hand side of such an
assignment, what you really assign to test is an address, in this case,
the address of the first character.
I suggest you try to explain your higher level goal instead. Why do you
want to use a pointer? What for? If this is really what you want:
Where do you want this pointer to point to?
If you want to declare a variable that is able to STORE string VALUES
much like an int variable is able to STORE some integer VALUE or a
double variable is able to STORE an approximation of a real VALUE,
`char*` is not the type you want but `std::string` is.
Nobody likes dealing with dynamic memory for string handling manually.
Some may say they do but I wouldn't believe them. ;-) Luckily, in C++
there are nicer alternatives. Consider getting a decent C++ book (like
Accelerated C++) so you can take advantage of the things that C++ has to
offer.
SG