how to convert char * to char []


how to convert char * to char [] ?

I have some code that receives data , a char *, using the #include <WinSock2.h> receive function. i would like to convert the data char * to char [].
So that i can split it into a vector of tokens of type char *.

As you can see ,

when i define str this way it works
//char str[] = "A bird came down the walk"; // this way works

but when i define str this way it does not work
const char * str2 = "A bird came down the walk"; // this way does not

is there anyway i can convert const char * to char [] ?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

#include <stdio.h>
#include <string.h>
#include <string>
#include <vector>
#include <iostream>

using namespace std;

int main()
{

	vector<char*> tokens; 

	char * token = NULL;
	//char str[] = "A bird came down the walk";  // this way works

	const char * str2 = "A bird came down the walk"; // this way does not 

	char *str  = (char *)str2; 

	rsize_t strmax = sizeof str;
	const char *delim = " ";
	char *next_token = NULL;
	//printf("Parsing the input string '%s'\n", str);
	token = strtok_s(str, delim, &next_token);
	while (token) {

		tokens.push_back(token);
		token = strtok_s(NULL, delim, &next_token);
	}


	for (auto x : tokens)
		cout << x << endl;

	cin.get();   

}
Last edited on
char str[] = "A bird came down the walk";
This means, declare an array of char called str, large enough to exactly hold that string plus the null terminator.

const char * str2 = "A bird came down the walk";
This means, declare a constant global string, and also declare a char pointer called str2 to point to it.

As the second one is constant, you cant use strtok() with it, as strtok() needs to modify the buffer you pass to it.
Last edited on
You can copy the string literal into a non-const array, and then use that array.

http://www.cplusplus.com/reference/cstring/strcpy/
Topic archived. No new replies allowed.