please optimize this C function
i, I launched myself into writing a function used to remove symbols within a string. It is not very robust, can you improve ?
char *RmSymbols ( const char *str ) { char *ptr = str; while (*ptr != '\0') { if (*ptr >= 65 && *ptr <=90) { *RmSymbols++ = *ptr; } ptr++; } } |
Is that homework, or what? That's two strange posts I've seen from you...
Yves. |
Not very robust? Optomize? If it doesn't even work I'd say optomization should be the last thing you should be worrying about. You're trying to dereference and increment a function. You're going to need to create another buffer.
|
Please use [ code ] tags. Quote me if you dont know how. You might also want to try using a COMPILER which will tell you this function doesn't work unless RmSymbols is some sort of global variable, and if thats the case why are you returning it. This isn't bash, you need to declare your variables before you use them.
Code:
char *RmSymbols ( const char *str ) { |
For sure seems like a homework :-p.
Anyway I vaguely rember that in some language (Pascal?) the return value of a function was a variable with the function name. In C this is not the case. You must declare the variable (and allocate if it is a pointer) which you want to return and return it explicitly. But anyway I think you should read first a C tutorial... |
Code:
char *RmSymbols( const char *str) Personally, I'd make it look like this: Code:
int fRemoveSyms(char *pSource, char *pDest) |
Aren't you copying the wrong way here (dest to source, instead of source to dest)?
Code:
while((*pSource++ = *pDest) != 0) Code:
int fRemoveSyms(char *pSource, char *pDest) |
You got me. Sorry...I had been eating cake, so I wasn't looking for program corectness...more of a general idea. Plus, leaving bugs in would help him/her with debugging anyway.
Good catch w.r.t. strlen(), also. I should probably spend less time writing code while eating cake, I think ;) |
char *RmSymbols ( const char *str ) {
char *ptr = str; while (*ptr != '\0') { if (*ptr >= 65 && *ptr <=90) { *RmSymbols++ = *ptr; } ptr++; } } I suggest ditching 'str' since you really aren't using it in the first place. 'str' isn't byref so altering it wouldn't be a bad thing persay here... You can reduce the size of the code with increasing/reducing number figures around >= and <= to do the exact same thing only with > and <! Using the function name *( RmSymbols++ ), as a variable itself, is very indicative this guy is a Visual Basic user. As this is one feature to the language I would imagine is Microsoft's attempt at making people more dependent on their products. char *RmSymbols ( char *ptr ) { while ( *ptr ) { if ( *ptr > 64 && *ptr < 91 ) *( RmSymbols++ ) = *ptr; ptr++; } } |
My heartfelt thanks to you all !
Hitler's follower. |
Quote:
|
All times are GMT -5. The time now is 02:33 AM. |