第2个回答 2013-08-28
void myremovespace(char * str)
{
char *p1, *p2;
char ch;
p1 = str; //first pointer
p2 = str; // second pointer to the remaining string
if (p1==NULL) return;
while (*p1)
{
if (*p1 != ' ')
{
ch = *p1;
*p2 = ch;
p1++;
p2++;
}
else
{
p1++;
}
}
*p2 = '\0';
}
int main(void)
{
char * str = "ab c dd e ";
char * str1;
str1 = (char*)malloc(20);
strcpy(str1,str);
char str2[]=" a bv cd ";
myremovespace(str1); //work
myremovespace(str2); //work
myremovespace(str); // not work
// because str is in a read-only memory.
//*p2 = ch will result in run-time error
}