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

int main() {    {
    char sir[3000];
    int i;
    int suma = 0;
    int lungime;

    scanf("%s", sir);

    lungime = strlen(sir);   

    char x;
    char *pX;

    x = sir[2];
    pX = &x;

    suma = atoi(pX); 
    return 0; 
} 

I am doing the adventOfCode, Day1. My problem is that I cannot pick certain digits from the string, using atoi. From what I read, atoi needs a pointer as argument.

if i read some big string like "111555434536563673673567367...." with a length between 2000 - 3000

I can't understand why when I print "suma", instead of printing the certain digit from my string, it prints some huge integer, like 83506.

kabanus
  • 24,623
  • 6
  • 41
  • 74

1 Answers1

1

From what I read, atoi needs a pointer as argument.

Needing a pointer is only part of the deal. The other part is that the pointer needs to point to a null-terminated string representing an integer.

Moreover, x = sir[2]; pX = &x is not how you get a pointer to the second element of sir[] array: x is a copy of the third digit (arrays are zero-based), and pX is a pointer to that copy.

If you want to get a numeric value of a single digit, subtract '0' from it (note single quotes around zero):

int thirdDigitVal = sir[2] - '0';

If you need to do it with atoi, copy the digit into a null-terminated string:

char copy[2] = {0};
copy[0] = sir[2];
int thirdDigitVal = atoi(copy);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523