l**n 发帖数: 88 | 1 Is there a problem with the following code?
char* strchr(char* s, char c)
{ for (char* p=s; *p; p++)
if (*p==c) return p;
return 0;
} |
r****o 发帖数: 1950 | 2 My thinking:
1. need to check if s is NULL
2. need to know the length of s, so the loop is only done within the length
of s.
【在 l**n 的大作中提到】 : Is there a problem with the following code? : char* strchr(char* s, char c) : { for (char* p=s; *p; p++) : if (*p==c) return p; : return 0; : }
|
g**u 发帖数: 583 | 3 I guess you need to modify the code, especially the logic to end the circle:
char *p;
for(p=s;p;p++)
{
if(c==*p)
return p;
}
return NULL; |
n*******s 发帖数: 482 | |
b**********r 发帖数: 46 | 5
logic error.
【在 l**n 的大作中提到】 : Is there a problem with the following code? : char* strchr(char* s, char c) : { for (char* p=s; *p; p++) : if (*p==c) return p; : return 0; : }
|
k********n 发帖数: 1819 | 6 I didn't see you change anything
circle:
【在 g**u 的大作中提到】 : I guess you need to modify the code, especially the logic to end the circle: : char *p; : for(p=s;p;p++) : { : if(c==*p) : return p; : } : return NULL;
|
r**u 发帖数: 1567 | 7 This is even worse than the original one. If s is not NULL, and if c is not
in s, then this loop will go over boundary and segment fault.
in Ansi C, you can't do something like:
for (char *p = s; *p; p++)
should be:
char *p;
for (p = s; *p; p++)
of course the top one is correct if you compiled it with g++.
circle:
【在 g**u 的大作中提到】 : I guess you need to modify the code, especially the logic to end the circle: : char *p; : for(p=s;p;p++) : { : if(c==*p) : return p; : } : return NULL;
|
h**k 发帖数: 3368 | 8 *p 和 *p != '\0' 应该是等价的吧?
C会自动把*p转成bool。当然这么写的编程风格极差。 |
g**u 发帖数: 583 | 9
not
In fact, the loop will not go forever, after reaching the end, p=='\0',
therefore the loop will end here.
In fact I tested two case: case 1: string is empty, case 2: c not in s, both
return NULL pointer. please correct me if I made mistake somewhere.
【在 r**u 的大作中提到】 : This is even worse than the original one. If s is not NULL, and if c is not : in s, then this loop will go over boundary and segment fault. : in Ansi C, you can't do something like: : for (char *p = s; *p; p++) : should be: : char *p; : for (p = s; *p; p++) : of course the top one is correct if you compiled it with g++. : : circle:
|
g**u 发帖数: 583 | 10
I did change a little bit, firstly the declaration is moved out of the loop,
which complies with C89,; another one is I compare the p to '\0', rather
than *p...
【在 k********n 的大作中提到】 : I didn't see you change anything : : circle:
|