大侠留步:关于strtol用法的奇怪问题,觉得是指针的问题,但是想不到具体的原因……
//////////////////////
//////strtol.cpp//////
//////////////////////
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
int main ()
{
char szNumbers[] = "2001 60c0c0 -1101110100110100100000 0x6fffff ";
char * pEnd =NULL;
long int li1, li2, li3, li4;
cout < < "The pEnd is: " < <pEnd < <endl;
li1 = strtol (szNumbers,&pEnd,10);
cout < < "The pEnd is: " < <pEnd < <endl;
li2 = strtol (pEnd,&pEnd,16);
cout < < "The pEnd is: " < <pEnd < <endl;
li3 = strtol (pEnd,&pEnd,2);
cout < < "The pEnd is: " < <pEnd < <endl;
li4 = strtol (pEnd,NULL,0);
cout < < "The pEnd is: " < <pEnd < <endl;
cout < < "The szNumbers is: " < <szNumbers < <endl;
cout < < "The decimal equivalents are: " < <li1 < < ", " < <li2 < < ", " < <li3 < < ", " < <li4 < <endl;
return 0;
}
[AccessGrid@AccessGrid ~]$ gcc -lstdc++ -g -o Test strtol.cpp
[AccessGrid@AccessGrid ~]$ ./Test
The pEnd is: [AccessGrid@AccessGrid ~]$
如果把那句
char * pEnd =NULL;
修改为
char * pEnd = ;
就会输出这样的结果
The pEnd is: ????}?+1 The pEnd is: 60c0c0 -1101110100110100100000 0x6fffff
The pEnd is: -1101110100110100100000 0x6fffff
The pEnd is: 0x6fffff
The pEnd is: 0x6fffff
The szNumbers is: 2001 60c0c0 -1101110100110100100000 0x6fffff
The decimal equivalents are:2001, 6340800, -3624224, 7340031
各位大侠,帮忙看看这个到底是什么原因
[解决办法]
char * pEnd =NULL;
long int li1, li2, li3, li4;
cout < < "The pEnd is: " < <pEnd < <endl;
-------------------------------------------------
你在没有调用strtol之前输出pEnd,结果是未定义的,因为pEnd指向的东西并没有经过strtol的设置。
[解决办法]
pEnd 在定义后,
没有赋值/初始化之前,
其值是随机的,
那么输出这个指针的内容,
自然也就是一堆乱码 ······