K******g 发帖数: 1870 | 1 char* func( char* a, const char* b )
{
while( *a )
{
char *s = a, *t = b;
while( (*s++ == *t++) && *s && *t );
if( *t == 0 )
return a;
a++;
}
return 0;
}
The above code was written to search for the first instance
of string "b" inside of string "a."
a. 请问以上代码是否有问题?解释
b. 怎么提高效率?
Question #2: |
t****a 发帖数: 1212 | 2 1. while( (*s++ == *t++) && *s && *t );
===> while(*s && *t && (*s++ == *t++));
2. No idea with this function. Would Anybody explain it? |
s*********t 发帖数: 1663 | 3 都是些经典错误
应该是通不过编译的
楼主自己敲一下就知道了
【在 K******g 的大作中提到】 : char* func( char* a, const char* b ) : { : while( *a ) : { : char *s = a, *t = b; : while( (*s++ == *t++) && *s && *t ); : if( *t == 0 ) : return a; : a++; : }
|
t*****5 发帖数: 22 | 4 1.
char* func( char* a, const char* b )
{
char* s=a;
for(;*s==*b;s++,b++)
if(*s=='\0')
return 0;
return a;
}
【在 K******g 的大作中提到】 : char* func( char* a, const char* b ) : { : while( *a ) : { : char *s = a, *t = b; : while( (*s++ == *t++) && *s && *t ); : if( *t == 0 ) : return a; : a++; : }
|
s*****t 发帖数: 737 | 5 2. need to check whether n is larger than the width of interger.
1<
though the compiler might already do that for you. |
s*********t 发帖数: 1663 | 6 that's some register checking on multi thread program
【在 s*****t 的大作中提到】 : 2. need to check whether n is larger than the width of interger. : 1<: though the compiler might already do that for you.
|
s*****t 发帖数: 737 | 7 What did you mean?
The code is to check the nth bit of (*p).
that's some register checking on multi thread program
【在 s*********t 的大作中提到】 : that's some register checking on multi thread program
|
c********t 发帖数: 1756 | 8
你这个不work;反例
char * a ="abcde";
char * b ="bc";
【在 t*****5 的大作中提到】 : 1. : char* func( char* a, const char* b ) : { : char* s=a; : for(;*s==*b;s++,b++) : if(*s=='\0') : return 0; : return a; : }
|
K******g 发帖数: 1870 | 9 能够列举出来吗?第一题是可以编译的
【在 s*********t 的大作中提到】 : 都是些经典错误 : 应该是通不过编译的 : 楼主自己敲一下就知道了
|
s*********t 发帖数: 1663 | 10 不能编译
const char* b;
char* t = b;
会报错
必须用const char* t = b;
【在 K******g 的大作中提到】 : 能够列举出来吗?第一题是可以编译的
|
|
|
s*********t 发帖数: 1663 | 11 while(*a)
也是经典错误
指针用之前没有判断有效
if(!a)
【在 K******g 的大作中提到】 : 能够列举出来吗?第一题是可以编译的
|
K******g 发帖数: 1870 | 12 请问怎么提高它的效率呢?
【在 s*********t 的大作中提到】 : while(*a) : 也是经典错误 : 指针用之前没有判断有效 : if(!a)
|
s*********t 发帖数: 1663 | 13 这是strstr()吧?
算法改成KMP算法,具体细节的去搜索一下吧,忘记了。
【在 K******g 的大作中提到】 : 请问怎么提高它的效率呢?
|
x****k 发帖数: 2932 | 14 第一道题可以用KMP 算法,但感觉面试时问KMP有点难了
第二道板上有人提过,实际上是用在embedded的环境中的,
p是个寄存器的地址,函数入口需要声明为volatile,循环检查第n bit是否被置为1,
严格的话还要一些入口参数检查。volatile会强迫编译器不能优化这段代码,每次循环
都需要重新读取 *p.
void wait(volatile int* p, int n )
{
assert(NULL != p)
while ((*p & (1 << n)) == 0);
} |
b********h 发帖数: 119 | 15
即使改成这样还是错的。(*s++ == *t++)会忽略掉最后一个字符。
比如说从abc中查找ac,仍然会返回abc。
【在 t****a 的大作中提到】 : 1. while( (*s++ == *t++) && *s && *t ); : ===> while(*s && *t && (*s++ == *t++)); : 2. No idea with this function. Would Anybody explain it?
|