C 中两个指针之间的距离
我有一个函数,它应该读取一个字符串(仅包含数字)并返回没有重复数字的最大序列。 例如: 12345267890
它应该返回: 345267890
我已经手动尝试了代码,我相信它应该可以工作。但是当我运行它时,当它到达这一行时 i=(strchr(v+i, *(v+j)))-v;
而不是获取指针之间的距离,我得到了一些东西像-1046583。我可以这样做吗?
char* bigSeq(char *v){
int i, j;
char *aux, *bgst;
aux=(char*) malloc(10*sizeof(char));
bgst=(char*) malloc(10*sizeof(char));
for(i=0;i<strlen(v);i++){
for(j=0;j<strlen(v+i);j++){
if(strchr(v+i, *(v+j)) != (v+j)){
if(strlen(strncpy(aux, (v+i),j)) > strlen(bgst))
strncpy(bgst, (v+i),j);
i=(strchr(v+i, *(v+j)))-v;
break;
}
}
}
return bgst;
}
I have a function that it is supposed to read a string (only with numbers in it) and return the biggest sequence that doenst have repeated numbers.
for example:
12345267890
it should return: 345267890
i've experimented the code manually and I believe it should work. but when I run it, and when it reaches this line i=(strchr(v+i, *(v+j)))-v;
instead of getting the distance between the pointers I get something like -1046583. can I do this?
char* bigSeq(char *v){
int i, j;
char *aux, *bgst;
aux=(char*) malloc(10*sizeof(char));
bgst=(char*) malloc(10*sizeof(char));
for(i=0;i<strlen(v);i++){
for(j=0;j<strlen(v+i);j++){
if(strchr(v+i, *(v+j)) != (v+j)){
if(strlen(strncpy(aux, (v+i),j)) > strlen(bgst))
strncpy(bgst, (v+i),j);
i=(strchr(v+i, *(v+j)))-v;
break;
}
}
}
return bgst;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您的问题在于
strchr()
以及当它找不到您正在搜索的字符时它返回的内容。在这种情况下,它返回 0,而不是传递给它的字符串的开头或结尾。您还应该回顾一下将输入设置为“
const char *
”,并了解为什么需要在两个循环的每次迭代中调用strlen()
。你可能可以做得更好。请注意,如果不重复数字的最长子串都是 10 位数字,则您分配的空间太小 - 您还需要为字符串末尾的 NUL
'\0'
分配一个字节。另外,strncpy()
不保证字符串以 null 结尾;我不确定这是否是您问题的一部分。I think your trouble is with
strchr()
and what it returns when it doesn't find the character you are searching for. In that case, it returns 0, not either the start or the end of the string that is passed to it.You should also review making the input a '
const char *
', and look at why you need to callstrlen()
on every iteration of the two loops. You can probably do better than that.Note that if the longest substring of non-repeating digits is all 10 digits, your allocated space is too small - you need to allocate a byte for the NUL
'\0'
at the end of the string too. Also,strncpy()
does not guarantee to null-terminate your string; I'm not sure whether that is part of your problem here.如果
j
是> 10
你正在覆盖不属于你的内存——这可能会导致各种有趣的问题。and
If
j
is> 10
you're overwriting memory you don't own - which can lead to all sorts of funny issues.我将建议一种 O(N) 算法,该算法也更简单、更易于阅读,并且除了堆栈上的一些指针和整数之外不需要额外的内存。这些功能有助于消除出错的可能性。
I'm going to suggest an O(N) algorithm which is also simpler, easier to read, and requires no extra memory other than a few pointers and integers on the stack. These features help remove possibilities for error.