Search code examples
ccharintatoi

convert array of characters to array of integers in C


I'm passing in an argument to a C program:

program_name 1234

int main (int argc, char *argv[]) {

    int     length_of_input = 0;    
    char*   input           = argv[1];


    while(input[length_of_input]) {
        //convert input from array of char to int
        length_of_input++;
    }
}

I want to be able to use each digit of the argument passed into the function separately as an integer. atoi(input[]) throws a compile-time error.

This code doesn't compile:

while(input[length_of_input]) {
    int temp = atoi(input[length_of_input]);
    printf("char %i: %i\n", length_of_input, temp);
    length_of_input++;
}

Solution

  • int i;
    for (i = 0; input[i] != 0; i++){
        output[i] = input[i] - '0';
    }