Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert char array to integer in C?

How can I convert the char array x to an integer 89 in the code below? Thank you

int main(int argc,char *argv[]){
    char y[13] = "0123456789012";
    char x[3];
    int integer_value;

    x[0] = y[8];
    x[1] = y[9];
    x[3] = '\0';

    integer_value=atoi(x);
}
like image 570
johan Avatar asked Nov 24 '25 17:11

johan


1 Answers

You're done; atoi() is one way of doing the conversion from a string to an integer. You could also use strtol() or sscanf().

UPDATE: Assuming, of course, that you fix the termination, i.e. set x[2] = '\0'; rather than x[3].

like image 123
unwind Avatar answered Nov 27 '25 08:11

unwind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!