I located a bug leading to runt-time error in my program that did sth. as follows:
1 2
char *pchar;
strcpy(pchar, "Class");
Can someone explain why? The 2nd parameter should be a pointer rather than a string literal. How come that compiler does not complain and the code just compiles? Thanks.
pchar is a pointer. Pointers are not strings. Pointers have to actually point to memory in order for them to be useful. Your pointer does not point to anything.
When you strcpy to pchar, you are copying that "Class" data to some random area in memory (because pchar points to random garbage), which is causing your program to explode.
Solutions:
1) use strings instead of char pointers. IE:
1 2
string str;
str = "Class"; // easy, safe
2) use a buffer
1 2
char buffer[40]; // buffer large enough to hold a string 39 characters long
strcpy(buffer,"Class");