Search code examples
clinuxatoi

string to char conversion by atoi from a defined index


Let's say I have char x[3] = "123"; and I would like to convert only index 1 and index2 "23" of the char array, can I do it by atoi?

I know I can do it by char z[2]; z[0]=x[1]; z[1]=x[2]; atoi(z); but it is not what I am asking for.


Solution

  • You can do this with

    char x[4];
    int i;
    
    strcpy(x, "123");
    i = atoi(x + 1);
    

    Because x is a pointer to char, x + 1 is a pointer to the next char. If you try to print with

    printf("%s", x + 1);
    

    You'l get 23 as the output.

    Note though that you need to declare the length of the char array to be one more than the number of characters in it - to accommodate the ending \0.