Search code examples
arrayscsubtraction

How do I subtract 1 from an array of integers


I am learning C in school, and I am having a little difficulty on my project. Basically, I am writing a function that gets a string containing a positive integer. The function subtracts 1 from that integer and puts the obtained value in the string.

So , if I have this ;

char nums[] = "2462";

how do I write a function that will subtract 1 from the integer, so that the result is "2461"??


Solution

  • First, convert the character array into an integer.

    You can use atoi (ASCII to Integer), but because it returns 0 on error there's no way to tell the difference between successfully converting "0" and an error.

    Instead use strtol (STRing TO Long integer).

    // end stores where parsing stopped.
    char *end;
    
    // Convert nums as a base 10 integer.
    // Store where the parsing stopped in end.
    long as_long = strtol(nums, &end, 10);
    
    // If parsing failed, end will point to the start of the string.
    if (nums == end) {
      perror("Parsing nums failed");
    }
    

    Now you can subtract, turn the integer back into a string with sprintf, and put it in nums.

    sprintf(nums, "%ld", as_long - 1);
    

    This is not entirely safe. Consider if nums is "0". It only has 1 byte of space. If we subtract 1 then we have "-1" and we're storing 2 characters where we only have memory for 1.

    For the full explanation of how to do this safely, see How to convert an int to string in C?.

    Alternatively, don't store it, just print it.

    printf("%ld", as_long - 1);