Search code examples
cparsingstrtol

C Parsing String Function Argument Using strtol


I'm a bit new to C and want to understand a few things about accessing function arguments using pointers and dereferencing.

Here's my code, the whole point of the program is to use strtol to parse a given parameter with only two digits separated by whitespaces.

int sum(const char *input){
  char *input = input_line;   // dereference the address passed into the function to access the string
  int i; // store sum in here
  char *rest; // used as second argument in strtol so that first int can be added to i
  i = strtol(input, &rest, 10); // set first int in string to i
  i += strtol(rest, &rest, 10); // add first and second int
  return i;
}

I'm confused how to access the string parameter given because strings have a * by the variable name, and I'm not too sure how to work around that.

Anyway, thanks.


Solution

  • There is no need to dereference the input parameter. If you simply drop the line

    char *input = input_line; 
    

    (which isn't the right way to dereference it anyways), the code will work. You are passing sum a pointer to char, which is exactly what the first argument to strol should be.

    A simple test:

    #include <stdio.h>
    #include <stdlib.h>
    
    int sum(const char *input){
      int i; // store sum in here
      char *rest; // used as second argument in strtol so that first int can be added to i
      i = strtol(input, &rest, 10); // set first int in string to i
      i += strtol(rest, &rest, 10); // add first and second int
      return i;
    }
    
    int main(void){
        char* nums = "23 42";
        printf("%d\n",sum(nums)); 
        return 0;
    }
    

    It prints 65 as expected.

    As far as the mechanics of dereferencing goes: If for some reason you really wanted to dereference the pointer passed to sum you would do something like this (inside sum):

    char ch; // dereferencing a char* yields a char
    ch = *input; // * is the dereference operator 
    

    Now ch would hold the first character in the input string. There is no reason at all to pass an individual char to strol hence such dereferencing is in this case pointless -- although there are of course valid reasons for sometimes in the body of a function dereferencing a pointer which is passed to that function.