Convert string to long using strtol and pointers

My goal is to convert a string such as "A1234" to long with a value of 1234 . My first step was to simply convert "1234" to long and it works as expected:

 #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; } 

Now I am having problems with pointers and trying to ignore A at the beginning of the line. I tried char* test = "A1234"; long val = strtol(test[1],NULL,10); char* test = "A1234"; long val = strtol(test[1],NULL,10); However, this causes the program to crash.

How to configure it so that it points to the right place?

+4
source share
1 answer

You are almost right. You need to pass a pointer to strtol , though:

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

or

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

Turning on some compiler warning flags would inform you of your problem. For example, from clang (even without adding additional flags):

 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. 

and from GCC:

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

Editorial: I think you can see from these error messages why beginners are often advised to use clang rather than GCC.

+7
source

Source: https://habr.com/ru/post/1493692/


All Articles