Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to long using strtol and pointers

My goal is to convert a string such as "A1234" to a long with value 1234. My first step was to just convert "1234" to a long, and that 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 trouble with pointers and trying to ignore the A at the beginning of the string. I have tried char* test = "A1234"; long val = strtol(test[1],NULL,10); however that crashes the program.

How do I set this up properly to get it pointing to the correct spot?

like image 643
user2461391 Avatar asked Feb 16 '23 18:02

user2461391


1 Answers

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 have told you your problem. For example, from clang (even with no special flags added):

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 note: I think you can see from these error messages why beginners are often well-advised to use clang rather than GCC.

like image 161
Carl Norum Avatar answered Feb 18 '23 11:02

Carl Norum