Mars wrote on 25/02/05 :
Your code commented (-ed-)
#include <stdio.h>
#include <string.h>
int main (void)
{
/* -ed-
* String literals are non-writable.
* Better to define them 'const'.
*/
char const *name = "Smith SYN is a man.";
char const *sure = "SyN";
/* -ed-
* To prevent temptations
* (because 's' is going to point to the string pointed by 'name'
*/
char const *s;
int x, y;
y = x = strlen (sure);
s = strstr (name, sure);
/* -ed-
* strstr() can fail.
* (Actually it does, because "SyN" is not "SYN",
* hence s is NULL and undefined behaviour
* when attempting to use it...
*/
for (; x > 0; x--)
{
/* -ed- missing {} are considered dangerous... */
if (s[y - x] >= 'a')
{
/* -ed-
* Now, we have a nice warning there :
main.c: In function `main':
main.c:29: warning: assignment of read-only location
* modifying is string literal invokes an undefined
behaviour...
* IOW, it's a bug. Don't do that, or use array of char
instead
* (and remove the 'const' qualifiers)
*/
s[y - x] = s[y - x] - 'a' + 'A';
/* -ed-
* I'm not sure what you are doing here.
* Note that 'a' + 'A' is meaningless and not portable
*/
putchar (s[y - x]);
}
else
{
putchar (s[y - x]);
}
/* -ed-
* It is silly to evaluate 4 times y - x when it is invariant.
* Do it once and stick the result in some local...
*/
}
putchar ('\n');
/* -ed- [C90] missing return some portable value */
return 0;
}
Try this :
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main (void)
{
char name[] = "Smith SYN is a man.";
char sure[] = "SYN"; /* SYN is not SyN... */
char *s = strstr (name, sure);
if (s != NULL)
{
int x, y;
y = x = strlen (sure);
for (; x > 0; x--)
{
if (s[y - x] >= 'a')
{
s[y - x] = s[y - x] - 'a' + 'A';
putchar (s[y - x]);
}
else
{
putchar (s[y - x]);
}
}
putchar ('\n');
}
/* Dev-c++ trick */
system ("pause");
return 0;
}
--
Emmanuel
The C-FAQ:
http://www.eskimo.com/~scs/C-faq/faq.html
The C-library:
http://www.dinkumware.com/refxc.html
"C is a sharp tool"