Portal Home > Knowledgebase > Articles Database > Simple C++ Question [Dynamic char allocation]
Simple C++ Question [Dynamic char allocation]
Posted by Barti1987, 01-15-2009, 07:12 PM |
I am trying to allocate new character string:
char *mystring;
mystring = new char[maxInput];
When I try to send it to a function by value, it won't work:
foo(&mystring);
void foo(char *string)
{
*string = "test";
}
Error that I get is:
cannot convert `char**' to `char*' for argument `1' to `void foo(char*)
Thanks for any hints.
Peace,
|
Posted by Xeentech, 01-15-2009, 08:29 PM |
Well.. a string isn't like an int, it's not a value stored in memory, right. So when you do *string = "hello, world"; you're not changing the value of *string to "...," are you? You need to think of it in terms of a pointer, not a "string."
You need to change the pointer to point to an area of memory that has the "hello, world," or what ever, string.
char** is a pointer to a pointer....
|
Posted by Barti1987, 01-16-2009, 02:25 PM |
char** is a pointer to a pointer....
That cleared some stuff.
I tried the following:
foo(mystring);
void foo(char *string)
{
*string = "test";
}
Then I got an error : invalid convert from const char* to char.
So its trying to convert from a pointer to a char, which is invalid. To fix it, I did this:
foo(mystring);
void foo(char *string)
{
string = "test";
}
Which loads OK but the value of mystring isn't actually changing.
Any ideas?
Thanks again,
|
Posted by Barti1987, 01-16-2009, 02:37 PM |
Let me ask a simpler question, it should clear things better for me:
char *myString;
myString = new char[maxSum];
The first line, we create a pointer to char?
The second line is creating a dynamic char in the pointer or address?
So basically:
mystring = ? (I think the value?)
&mystring = ? (I think the address location)
*mystring = ?
Thanks,
|
Posted by Barti1987, 01-16-2009, 08:48 PM |
Finally got it to work.. Just changed the declaration to:
void foo(char **string);
Peace,
|
Add to Favourites Print this Article
Also Read