2013-07-26 39 views
4

我的目标是将诸如"A1234"之类的字符串转换为值为1234long。我的第一个步骤是只是转换"1234"long,并且按预期工作:使用strtol和指针将字符串转换为long

#include <stdio.h> 
#include <stdlib.h> 
int main(int argc, char **argv) 
{ 
    char* test = "1234"; 
    long val = strtol(test,NULL,10); 
    char output[20]; 
    sprintf(output,"Value: %Ld",val); 
    printf("%s\r\n",output); 
    return 0; 
} 

现在我有麻烦的指针,并试图忽略A在字符串的开头。我曾尝试char* test = "A1234"; long val = strtol(test[1],NULL,10);但是导致程序崩溃。

如何正确设置它以使其指向正确的位置?

回答

7

您是差不多吧。您需要将指针传递给strtol,虽然:

long val = strtol(&test[1], NULL, 10); 

long val = strtol(test + 1, NULL, 10); 

打开一些编译器警告标志会告诉你你的问题。例如,从铛(即使不加特殊标志):

example.c:6:23: warning: incompatible integer to pointer conversion passing 
     'char' to parameter of type 'const char *'; take the address with & 
     [-Wint-conversion] 
    long val = strtol(test[1],NULL,10); 
         ^~~~~~~ 
         & 
/usr/include/stdlib.h:181:26: note: passing argument to parameter here 
long  strtol(const char *, char **, int); 
          ^
1 warning generated. 

,并从GCC:

example.c: In function ‘main’: 
example.c:6: warning: passing argument 1 of ‘strtol’ makes pointer from integer 
without a cast 

编者按:我认为你可以从这些错误消息为什么初学者往往是良好建议使用clang而不是GCC。