玩指针:
char a[]=" 0xa this is a343 good";
char* *endptr=NULL;
long int b=0;
b=strtol(a,endptr,0);
b=strtol(*endptr,endptr,0);为什么在最后一行中出现分段错误?*endptr是char *还是?如果我在这里很好地理解了strtol的行为,它将读取第一个整数10,然后*endptr将指向0xa之后的下一个空格。我说得对吗?
发布于 2017-02-12 17:36:01
您的崩溃与strtol无关。问题是,您取消引用具有值NULL的指针。这是非法的,并导致崩溃(seg故障)。
你的问题是:
b=strtol(*endptr,endptr,0);
^^^^^^^
Dereference a NULL leads to a crash您的问题与以下代码相同:
char** endptr=NULL;
char* p = *endptr; // Crash!!因此,您的问题实际上与strtol无关。
关于strtol
如果希望strtol更新*endptr,则需要传递一个值,即而不是 NULL。
这样做的方法是创建一个char*变量(注意:而不是a char**)并将*地址** char*传递给strtol。
比如:
char a[]=" 0xa this is a343 good";
char* p; // Notice: just one * as you need a pointer to char
long int b=0;
b=strtol(a, &p,0);
^^
Notice: & (aka address of). So you pass the address of
a pointer to char. Equivalent to char** as expected
by strtol发布于 2017-02-12 17:31:58
在您的程序endptr = NULL中,这一行将抛出和异常: b=strtol(*endptr,endptr,0);
查看函数的定义:http://www.cplusplus.com/reference/cstdlib/strtol/
您不应该使用双指针:
试着做这样的事情:
char a[] = " 0xa this is a343 good";
char* endptr = NULL;
long int b = 0;
b = strtol(a, &endptr, 16);
b = strtol(endptr, &endptr, 16);https://stackoverflow.com/questions/42190693
复制相似问题