Reputation: 65
string result="CCY 1.2597 Down 0.0021(0.16%) 14:32 SGT [44]";
char* token;
char* buffer[result.length() + 1]; //Space for '\0'
strcpy(buffer, result.c_str());
buffer[result.length()] = '\0'; //insert '\0'
token = strtok(buffer, " ");
while (token != NULL) {
/* work with token */
token = strtok(NULL, " ");
}
I not sure why the above code got error, what is wrong with my code
main.cpp:51:30: error: cannot convert ‘char**’ to ‘char*’ for argument ‘1’ to ‘char* strcpy(char*, const char*)’
main.cpp:53:27: error: cannot convert ‘char**’ to ‘char*’ for argument ‘1’ to ‘char* strtok(char*, const char*)’
make: *** [main.o] Error 1
BUILD FAILED (exit value 2, total time: 893ms)
Upvotes: 0
Views: 412
Reputation: 36049
You have two problems with your code: Firstly, the variable type for buffer
is wrong, which is the error the compiler finds. Secondly, you are (probably unknowingly) deviating from the C++ standard by using the non-standard variable length array (VLA) extension of the gcc. This feature is standard in C from C99 on, but not in C++.
For the variable declaration, the following line is wrong:
char* buffer[result.length() + 1];
This line allocates an array of pointers to characters on the stack. However, strcpy
expects a single pointer to a character vector. While an array type (like char[]
) decays into a pointer (char*
), an array of pointers to characters (char*[]
) decays into char**
, which is one pointer too many. Declare instead:
char buffer[result.length() + 1];
Now, this will still compile only on gcc. To make your code compatible, you'll have to make the memory allocation dynamic, e.g. by using:
char *buffer = new char[result.length() + 1];
and then performing
delete[] buffer;
at the end of your routine. You should use smart pointers (std::unique_ptr
) to make your life easier here.
Upvotes: 4
Reputation: 5331
Your definition
char* buffer[result.length() + 1];
is wrong.
char* buffer = new char[result.length() + 1];
You have to initialize the c-string with dynamic memory allocation.
Upvotes: 1
Reputation: 1685
Declaration off buffer
is wrong. Get rid of the '*'.
It should be
char buffer[result.length() + 1];
Upvotes: 0
Reputation: 92271
The buffer
should not be char*
, but just char
.
It will contain the characters, not point to them.
Upvotes: 0