Statement *p++ = *source++; in the following first program doesn’t cause any errors but causes the error ISO C++ forbids cast to non-reference type used as lvalue in the second program when compiled. Why does this happens?
-
The first program
#include char *my_strcpy(char *destination, char *source) { char *p = destination; while (*source != '\0') { *p++ = *source++; } *p = '\0'; return destination; } int main() { char source[] = "A string to be used for demonstration purposes"; char destination[80]; my_strcpy(destination, source); puts(destination); return 0; } -
The second program
#include char source[] = "A string to be used for demonstration purposes"; char destination[80]; int main() { char *p = destination; putchar('\n'); while(*source != '\0') { *p++ = *source++; } *p = '\0'; puts(destination); return 0; }
This happens because your first program increments a pointer, while in the second program you apply the
++operator to an array. Although arrays often behave like pointers, they are not pointers. Arrays support pointer arithmetics, but they do not support pointer operators that treat them aslvalue(i.e. attempt to modify where they point).Fixing the problem is trivial – simply create a pointer that points to the array, and use that pointer in your loop, like this: