3

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);
}
5
  • 1
    Should be x[2] = '\0';, rather than x[3], but apart from that, that works. What is the question? Commented Jun 19, 2012 at 15:30
  • 1
    Should be x[2] = '\0';, x[3] is out of bounds. Commented Jun 19, 2012 at 15:30
  • 2
    the code you wrote does exactly what you are asking... just x[2]='\0' Commented Jun 19, 2012 at 15:31
  • Also, y is one too short as there is a null character in a string literal. Commented Jun 19, 2012 at 15:32
  • sorry, I don't know how I missed x[3] :( Commented Jun 19, 2012 at 15:34

1 Answer 1

6

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].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.