1

I am having character array with integer elements for example data[4]={"1234"}. I want to convert it into integer elements . There could be most simple way i.e.subtract 48 from each array element to get corresponding integer number. Here ,I am using atoi() function but not getting expected result.Current output: 1234 , 234 , 34 , 4

Expected output: 1 , 2 , 3 , 4 How should I get it?

#include<stdio.h>
#include<string.h>

int main(void)
{
  int num0;
  int num1;
  int num2;
  int num3;
  char data[6]={"1234"};

  num0 =atoi(&data[0]);
  printf("num0 =%d\n",num0);

  num1 =atoi(&data[1]);
  printf("num1 =%d\n",num1);

  num2 =atoi(&data[2]);
  printf("num2 =%d\n",num2);

  num3 =atoi(&data[3]);
  printf("num3 =%d\n",num3);
  return 0;
}
3
  • regarding; data[4]={"1234"} This is wrong. That literal "1234" takes 5 characters (remember that trailing NUL byte) Commented Aug 5, 2020 at 19:56
  • the posted code does not cleanly compile! running the posted code through the compiler results in: untitled1.c:12:7: warning: implicit declaration of function ‘atoi’ [-Wimplicit-function-declaration] This is because the posted code is missing the statement: #include <stdlib.h> Commented Aug 5, 2020 at 19:59
  • 2
    OT: when initializing an array via a literal, it is (usually) best to let the compiler determine the size of the array. Suggest: char data[] = { "1234" }; Commented Aug 5, 2020 at 20:04

1 Answer 1

10

atoi uses all the string to do the conversion, not only the first character. Then

  • &data[0] is databeing "1234" => atoi(&data[0])returns 1234
  • &data[1] is data+1being "234" => atoi(&data[1])returns 234
  • &data[2] is data+2being "34" => atoi(&data[2])returns 34
  • &data[3] is data+3being "4" => atoi(&data[3])returns 4

you want to do something like data[i] - '0' where i is 0 .. 3

#include <stdio.h>

int main(void)
{
  char data[] = {"1234"}; /* or const char * data = "1234" */
  int i;

  for (i = 0; i != 4; i += 1)
    printf("num%d = %d\n", i+1, data[i] - '0');

  return 0;
}

Compilation and execution :

pi@raspberrypi:/tmp $ gcc -Wall c.c
pi@raspberrypi:/tmp $ ./a.out
num1 = 1
num2 = 2
num3 = 3
num4 = 4
pi@raspberrypi:/tmp $ 

Out of that I encourage you to stop to use atoi because atoi("aze") returns 0 without signaling an error. Instead you can use strtol or scanf with the format "%d" checking scanf returns 1.

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.