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.

1
  • 1
    Don't use atoi. Use strtol instead Commented Dec 31, 2017 at 14:47

1 Answer 1

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);
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.