If char*s are read only, why can I overwrite them?

The presented code snippet does not change the string literals themselves. It only changes the values stored in the pointer fruit. You can imagine these lines char* fruit = “banana”; fruit = “apple”; the following way char unnamed_static_array_banana[] = { ‘b’, ‘a’, ‘n’, ‘a’, ‘n’, ‘a’, ‘\0’ }; char *fruit = &unnamed_static_array_banana[0]; char unnamed_static_array_apple[] = … Read more

C Strings Comparison with Equal Sign

I thought that c strings could not be compared with == sign and I have to use strcmp Right. I though that this was wrong because it is like comparing pointers so I searched in google and many people say that it’s wrong and comparing with == can’t be done That’s right too. So why … Read more

How do you convert CString and std::string std::wstring to each other?

According to CodeGuru: CString to std::string: CString cs(“Hello”); std::string s((LPCTSTR)cs); BUT: std::string cannot always construct from a LPCTSTR. i.e. the code will fail for UNICODE builds. As std::string can construct only from LPSTR / LPCSTR, a programmer who uses VC++ 7.x or better can utilize conversion classes such as CT2CA as an intermediary. CString cs … Read more

Can a std::string contain embedded nulls?

Yes you can have embedded nulls in your std::string. Example: std::string s; s.push_back(‘\0’); s.push_back(‘a’); assert(s.length() == 2); Note: std::string‘s c_str() member will always append a null character to the returned char buffer; However, std::string‘s data() member may or may not append a null character to the returned char buffer. Be careful of operator+= One thing … Read more

Why do I first have to strcpy() before strcat()?

strcat will look for the null-terminator, interpret that as the end of the string, and append the new text there, overwriting the null-terminator in the process, and writing a new null-terminator at the end of the concatenation. char stuff[100]; // ‘stuff’ is uninitialized Where is the null terminator? stuff is uninitialized, so it might start … Read more

C – split string into an array of strings

Since you’ve already looked into strtok just continue down the same path and split your string using space (‘ ‘) as a delimiter, then use something as realloc to increase the size of the array containing the elements to be passed to execvp. See the below example, but keep in mind that strtok will modify … Read more

Proper way to copy C strings

You could use strdup() to return a copy of a C-string, as in: #include <string.h> const char *stringA = “foo”; char *stringB = NULL; stringB = strdup(stringA); /* … */ free(stringB); You could also use strcpy(), but you need to allocate space first, which isn’t hard to do but can lead to an overflow error, … Read more