使用strtol和指针将字符串转换为长整型

4

我的目标是将像 "A1234" 这样的字符串转换为值为 1234long类型。 我的第一步是将 "1234" 转换为 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); 但是程序崩溃了。

请问如何正确设置以便将其指向正确的位置?
1个回答

8

你的理解基本正确。然而,你需要传递一个指向 strtol 的指针:

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

或者

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

开启一些编译器警告标志可以让你发现问题。例如,使用clang编译(即使没有添加任何特殊标志):

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。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接