mi************@advalvas.be (=?ISO-8859-1?Q?Micha=EBl_Boland?=) wrote:
I have a fonction to trim a string :
char *trimstr(char *pbuf1)
{
char *pbuf2 , *pbuf3;
pbuf2 = pbuf1 ;
pbuf3 = pbuf1 ;
while(*pbuf1 != '\0') { if(*pbuf1 != ' ') { pbuf2 = pbuf1; pbuf2++; }
pbuf1++; }
while(*pbuf2 != '\0') { *pbuf2 = '\0'; pbuf2++; }
return(pbuf3) ;
}
That's a funny way to write a trimming function, but let that be...
main(int argc, char *argv[], char *env[])
This is not a valid declaration of main(). Main is either
int main(void)
or
int main(int argc, char **argv)
or anything equivalent; it cannot take a third argument in ISO C. In
C99, implicit int is out as well, but you've probably got a C89
compiler, so that's OK.
{
trimstr(" tata ");
return 0;
}
It's ok with Unix Digital.
Only by accident.
The result with Linux is Segmentation fault.
I think the problem is " tata " is a const *char
Not quite; it's a non-modifiable array of char. For historical and
convenience reasons, it isn't actually const. And in this case, the
convenience just happens to be inconvenient :-(
and C Linux don't allow to change a constant.
Correct. And rightly so.
Is it possible in the function trimstr to know if the argument is a
*char or a const *char?
No. That is, yes; if it _had_ been a const char *, you would have had a
compile-time diagnostic. But since string literals aren't actually
const-qualified, there is no way to tell. Just don't pass string
literals to functions which modify them; it invokes undefined behaviour,
and the effects may range from accidentally working, through seeming to
work but doing nothing, causing a segfault, and in theory mailing lurid
proposals to Elio Di Rupo. So just don't do that.
Oh, btw: it's a char *, not a * char.
Richard