使用strtol和指针将字符串转换为long

use*_*391 4 c string pointers strtol

我的目标是一个字符串转换,如"A1234"long同值1234.我的第一步是转换"1234"为a 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;
}
Run Code Online (Sandbox Code Playgroud)

现在我遇到指针问题并试图忽略A字符串的开头.char* test = "A1234"; long val = strtol(test[1],NULL,10);然而,我已经尝试过崩溃程序.

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

Car*_*rum 8

你几乎是对的.但是,您需要将指针传递给strtol:

long val = strtol(&test[1], NULL, 10);
Run Code Online (Sandbox Code Playgroud)

要么

long val = strtol(test + 1, NULL, 10);
Run Code Online (Sandbox Code Playgroud)

打开一些编译器警告标志会告诉你你的问题.例如,来自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.
Run Code Online (Sandbox Code Playgroud)

来自海湾合作委员会:

example.c: In function ‘main’:
example.c:6: warning: passing argument 1 of ‘strtol’ makes pointer from integer 
without a cast
Run Code Online (Sandbox Code Playgroud)

编辑说明:我认为你可以从这些错误信息中看出为什么初学者通常建议使用clang而不是GCC.