本文介绍了strtok上的段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




..以下会导致段错误。 ..没有

知道为什么?!


int main(){

char name [15];

strcpy(name," ab8bc8cd8ed");


char cur [800];

strcpy(cur,strtok(name) ,8));


while(cur){

printf(" Output:%s \ n",cur);

printf(" Stringlength%i \ n",strlen(cur));

strcpy(cur,strtok(0," 8"));

printf(" next \ n");

}


}


输出:-----------------------


输出:ab

Stringlength 2

next

输出:bc

Stringlength 2

next

输出: cd

Stringlength 2

next

输出:ed

Stringlength 2

Segmentationfault

------------------------------


感谢您的帮助

问候

Fatih Gey

解决方案



检查strtok()的返回值。当没有

更多令牌时,它返回NULL。 NULL在< stdlib.h>中定义。


干杯,

Andreas

-

Andreas K?h?ri




(严格来说)说来,该行上的零应该是一个空的
指针)




0转换为指针*是*空指针。

在这里使用0没有错。


-Kevin

-

我的电子邮件地址有效,但会定期更改。

要联系我,请使用最近发布的地址。





NULL也在stdio.h和string.h中定义,

以及其他头文件。


stddef.h有NULL宏和_t typedef。

NULL和所有其他宏和typedef,

也在每个头文件中定义,对于任何函数都有原型

,定义为

能够接受他们[NULL和朋友],作为参数,

或将它们作为值返回。


-

pete

Hi,

.. following causes a segfault. .. didn''t
know why ?!

int main() {
char name[15];
strcpy (name, "ab8bc8cd8ed");

char cur[800];
strcpy (cur, strtok(name, "8"));

while (cur) {
printf ("Output: %s\n", cur);
printf ("Stringlength %i\n", strlen(cur));
strcpy(cur,strtok(0, "8"));
printf ("next\n");
}

}

output: -----------------------

Output: ab
Stringlength 2
next
Output: bc
Stringlength 2
next
Output: cd
Stringlength 2
next
Output: ed
Stringlength 2
Segmentationfault
------------------------------

Thanks for any help
Regards
Fatih Gey

解决方案


Check the return value of strtok(). It returns NULL when no
more tokens remains. NULL is defined in <stdlib.h>.

Cheers,
Andreas
--
Andreas K?h?ri



(strictly speaking, the zero on that line should be a null
pointer)



0 converted to a pointer *is* a null pointer. There''s nothing wrong with
using 0 here.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.




NULL is also defined in stdio.h and string.h,
as well as in other header files.

stddef.h has the NULL macro and the _t typedefs.
NULL and all of the other macros and typedefs,
are also defined in each header file that has a prototype
for any function, which is defined as either
being able to accept them [NULL and friends], as arguments,
or return them as values.

--
pete


这篇关于strtok上的段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 20:39