I am working on Microsoft Visual Studio environment. I came across a strange behavior
char *src ="123";
char *des ="abc";
printf("\nThe src string is %c", src[0]);
printf("\tThe dest string is %c",dest[0]);
des[0] = src[0];
printf("\nThe src string is %c", src[0]);
printf("\tThe dest string is %c",dest[0]);
The result is:
1 a
1 a
That means the des[0] is not being initialized. As src is pointing to the first element of the string. I guess by rules this should work.
Since src and des are initialized with string literals, their type should actually be
const char *, notchar *; like this:There was never memory allocated for either of them, they just point to the predefined constants. Therefore, the statement
des[0] = src[0]is undefined behavior; you’re trying to change a constant there!Any decent compiler should actually warn you about the implicit conversion from
const char *tochar *…If using C++, consider using
std::stringinstead ofchar *, andstd::coutinstead ofprintf.