If it is a string literal, you can do either of these:
char *string = "abcd";
char astring[] = "abcd";
If you want to know this for eventually copying strings, you can either have a buffer, or allocate memory, and space for '\0' is necessary, even though strlen("abcd")
will return 4 because it does not count the terminator.
/* buffer way */
char string[5];
strcpy(string, "abcd");
/* allocating memory */
// char *ptr = malloc(5*sizeof(*ptr)); // question was retagged C++
char *ptr = static_cast<char*>(malloc(5*sizeof(*ptr));
strcpy(ptr,"abcd");
/* more stuff */
free(ptr);
Since the question has been retagged to C++, you can also use new
and delete
.
/* using C++ new and delete */
char *ptr = new char[5]; // allocate a block of 5 * sizeof(char)
strcpy(ptr, "abcd");
// do stuff
delete [] ptr; // delete [] is necessary because new[] was used
Or you could also use std::string
.