Originally Posted by
alice
I want to change the function prototype to
Code:
int trimString(char* str);
am my code correct? thk a lot.
No
Code:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int trimString(char* str);
{
char *str = malloc(30); // redefinition of str. Try the statement below
char *p, *end;
str = malloc(30); // this is in the proper place
*str = '\0'; // Why? Just use strcpy() instead
strcat(str, " abcd EFGH ");
end = str + (strlen(str) - 1);
while (isspace((unsigned char)*end)) {
--end;
}
*++end = '\0';
p = str;
while (isspace((unsigned char)*p)) {
++p;
}
puts(p);
free(p); // Confusing and wrong. You malloc'd str so release str
return 0;
}
[edit]
Oh, and why are you passing in the pointer to str and then throwing away everything it points to? For testing wouldn't it be better to do:
Code:
int main()
{
char *str;
str = malloc(30);
strcpy(str, " abcd EFGH ");
int trimString(str);
free(str);
return 0;
}
int trimString(char* str);
{
char *end, p;
end = str + (strlen(str) - 1);
while (isspace((unsigned char)*end))
{
--end;
}
*++end = '\0';
p = str;
while (isspace((unsigned char)*p))
{
++p;
}
puts(p);
return 0;
}
The fact that you are changing str can be dealt with next, when you pass back the new string instead of outputting it in the function.
[/edit]