奇怪指针
代码如下:
static int Index_NoKMP(char * source,char * target,int pos)
{
int spos=pos;
if(spos <0 || spos> strlen(source))
{
printf( "位置不合法\n ");
return CHECKERROR;
}
char *ps=source; // (1)
char *pt=target; // (2)
while(*ps!= '\0 ' && *pt!= '\0 ')
{
if(*ps==*pt) //
{
ps++;
pt++;
}
else
{
ps=source+(ps-pt)+1;
pt=target; /*每次不匹配的时候指向模式字符串的指针都回朔到开头*/
}
}
int beginpos=(int)(ps-pt);
if(0 <beginpos <strlen(source))
{
return beginpos;
}
else
{
return CHECKERROR;
}
}
*************************************************************
以上是一个简单的模式匹配算法, 问题是当我调用此函数的时候 (1)处出错
提示说bad pointer? 而(2)处是正确的,而且(2)处的值都是对的。 为什么呢?好奇怪
我用的是vs2003
[解决办法]
ps=source+(ps-pt)+1;
int beginpos=(int)(ps-pt);
这两句有问题 这两个指针起点地址不一样的。
改成
ps = source + (ps - pt) + 1 - source + target;
int beginpos = (int)(ps - pt) - (int)(source - target);
[解决办法]
什么意思,看不出来什么意思?
ps = source + (ps - pt) + 1 - source + target;//化简后为:
ps = (ps - pt) + 1 + target;
int beginpos = (int)(ps - pt) - (int)(source - target);//化简为:
int beginpos = (ps - source) + (target - pt);
不知道是什么用意,即使转换为上面的代码还是不明确
个人感觉:
首先ps-pt以及source - target是什么意思,如果target的地址和source的地址没有什么关系的话,这样操作没有什么用,而且还会引起不确定的错误。
一般的搜索算法在这里应该采用下标的做法吧 ,即时要相减也要source相关指针和target相关指针各自做减运算吧
开始的出错可以尝试在编译器中rebuild all再调试,有时候build并不会使得代码正确编译(汗MS的编译器),导致调试信息总的符号不能和源代码一致。
另外你说1处出错,2处怎么还能执行呢?