Bird
Raised Fist0
DSA Cprogramming~10 mins

String to Integer atoi in DSA C - Execution Trace

Choose your learning style10 modes available
Concept Flow - String to Integer atoi
Step 1: Skip spaces
i=0,1 → ' ' skipped → i=2
↓
Step 2: Read sign
s[2]='-' → sign=-1 → i=3
↓
Step 3: Accumulate digits
s[3]='4' → result=4
↓
Step 4: Apply sign + clamp
-1 × 42 = -42
C's atoi processes the string in four strict sequential steps: skip whitespace, detect optional sign, accumulate digit characters left to right, then apply sign and clamp to INT_MAX/INT_MIN. The critical C-specific concern is overflow detection before multiplying — signed integer overflow is undefined behavior in C.
Execution Sample
DSA C
#include <ctype.h>
#include <limits.h>

int myAtoi(char *s) {
    int i = 0;
    /* Step 1: skip whitespace */
    while (s[i] == ' ') i++;
    /* Step 2: read sign */
    int sign = 1;
    if (s[i] == '+' || s[i] == '-') {
        sign = (s[i] == '-') ? -1 : 1;
        i++;
    }
    /* Step 3: accumulate digits with overflow check */
    int result = 0;
    while (isdigit((unsigned char)s[i])) {
        int digit = s[i] - '0';
        if (result > (INT_MAX - digit) / 10) {
            return sign == 1 ? INT_MAX : INT_MIN;
        }
        result = result * 10 + digit;
        i++;
    }
    return sign * result;
}
Trace on ' -42abc': i advances past 2 spaces (i=2), reads '-' setting sign=-1 (i=3), reads '4' → result=4 (i=4), reads '2' → result=42 (i=5), hits 'a' which fails isdigit so loop exits. Returns -1 × 42 = -42.
Execution Table
is[i]actionsignresultoverflow?
0' 'skip space10no
1' 'skip space10no
2'-'sign=-1, i++-10no
3'4'result=0*10+4=4-14no
4'2'result=4*10+2=42-142no
5'a'!isdigit: STOP-142no
--return -1*42-1-42no
💡 Loop exits at i=5 because isdigit('a') returns 0. Final value: sign * result = -1 * 42 = -42.
Variable Tracker
stepisignresultdigitcheck: result>(INT_MAX-d)/10
init010--
skip spaces210--
read sign3-10--
read '4'4-1440>(2147483643)/10=214748364? NO
read '2'5-14224>(2147483645)/10=214748364? NO
stop 'a'5-142--
return--1-42--
Key Moments - 4 Insights
Why cast to (unsigned char) inside isdigit((unsigned char)s[i])?
isdigit takes an int but expects a value in the range [0, 255] or EOF. If char is signed and s[i] is a negative value (extended ASCII > 127), passing it directly is undefined behavior. Casting to unsigned char ensures a valid non-negative value.
Why check result > (INT_MAX - digit) / 10 instead of result * 10 + digit > INT_MAX?
result * 10 itself can overflow before adding digit — signed integer overflow is undefined behavior in C. The rearranged check avoids the multiplication entirely, testing only with safe operations.
What does C's standard atoi() return for overflow — and why should you not use it?
Standard atoi() has undefined behavior on overflow. It should never be used in production or competitive programming. strtol() is the correct alternative — it sets errno and clamps to LONG_MIN/LONG_MAX on overflow.
What does the algorithm return for input '+-12'?
Reads '+', sets sign=1, advances i. Next character '-' is not a digit so the digit loop never runs. Returns 1 * 0 = 0.
Visual Quiz - 4 Questions
Test your understanding
For input ' +0 123', what does myAtoi return?
A123
B0
C0123
D-1
💡 Hint
The digit loop stops at the first non-digit after accumulating '0' — the space after '0' terminates digit reading.
For input '2147483648' (INT_MAX + 1), what does myAtoi return?
A-2147483648
B2147483648
C2147483647
D0
💡 Hint
The overflow check fires before result would exceed INT_MAX and clamps to INT_MAX = 2147483647.
Why is isdigit((unsigned char)s[i]) safer than s[i] >= '0' && s[i] <= '9' in C?
Aisdigit is faster
Bisdigit handles multi-byte characters
Cisdigit with unsigned char cast avoids UB on signed char values > 127
DThey are exactly equivalent in all cases
💡 Hint
isdigit expects [0,255] or EOF — passing a signed negative char value directly is UB in C.
What does myAtoi return for '-2147483649' (below INT_MIN)?
A-2147483649
B2147483647
C0
D-2147483648
💡 Hint
Negative overflow clamps to INT_MIN = -2147483648 because sign == -1 in the overflow branch.
Concept Snapshot
C atoi = 4 steps: skip spaces → read sign → accumulate digits (stop on first non-digit) → clamp to [INT_MIN, INT_MAX]. Key C rules: (1) signed overflow is UB — check before multiplying, (2) cast to unsigned char before isdigit, (3) never use stdlib atoi() — it has UB on overflow.
Full Transcript
Let's trace String to Integer atoi in C on ' -42abc'. i starts at 0. s[0] and s[1] are spaces — the while loop advances i to 2. At i=2 we see '-'. We set sign to -1 and advance i to 3. Now the digit loop starts. At i=3, s[3]='4'. We cast to unsigned char before calling isdigit — this is essential in C to avoid undefined behavior. digit = '4' - '0' = 4. Overflow check: is 0 > (INT_MAX - 4) / 10? That's 0 > 214748364 — false. result = 0*10+4 = 4. Advance to i=4. At i=4, s[4]='2'. digit=2. Overflow check: is 4 > 214748364? No. result = 42. Advance to i=5. At i=5, s[5]='a'. isdigit returns 0. Loop exits. Return sign * result = -1 * 42 = -42. The two C-specific rules to remember: always cast to unsigned char before isdigit, and always check overflow before the multiplication to avoid undefined behavior.

Practice

(1/5)
1. What does the atoi function do in C programming?
easy
A. Checks if a string contains only digits
B. Converts a string representing a number into an integer
C. Calculates the length of a string
D. Converts an integer into a string

Solution

  1. Step 1: Understand the purpose of atoi

    The atoi function stands for ASCII to integer, which means it converts a string of digits into an integer value.
  2. Step 2: Compare options with definition

    Only Converts a string representing a number into an integer correctly describes this conversion from string to integer.
  3. Final Answer:

    Converts a string representing a number into an integer -> Option B
  4. Quick Check:

    atoi = string to integer conversion [OK]
Hint: Remember atoi means ASCII to integer conversion [OK]
Common Mistakes:
  • Confusing atoi with itoa (integer to ASCII)
  • Thinking atoi calculates string length
  • Assuming atoi validates string digits
2. Which of the following is the correct syntax to use atoi in C?
easy
A. int num = atoi(char *str);
B. int num = atoi();
C. int num = atoi(int str);
D. int num = atoi(str);

Solution

  1. Step 1: Check function parameter type

    The atoi function takes a single argument of type const char *, which is a string pointer.
  2. Step 2: Validate correct syntax

    int num = atoi(str); correctly shows calling atoi with a string variable str without specifying type in call.
  3. Final Answer:

    int num = atoi(str); -> Option D
  4. Quick Check:

    atoi takes string variable as argument [OK]
Hint: Call atoi with just the string variable name [OK]
Common Mistakes:
  • Including type in function call parentheses
  • Calling atoi without arguments
  • Passing integer instead of string
3. What will be the output of the following C code?
char str[] = "-123abc";
int val = atoi(str);
printf("%d", val);
medium
A. -123
B. 0
C. 123
D. Error

Solution

  1. Step 1: Analyze atoi behavior with mixed string

    atoi converts initial numeric part including sign until non-digit character. Here, "-123" is converted, stops at 'a'.
  2. Step 2: Determine output value

    So, val becomes -123 and printf prints -123.
  3. Final Answer:

    -123 -> Option A
  4. Quick Check:

    atoi stops at first non-digit, returns -123 [OK]
Hint: atoi reads number until first non-digit character [OK]
Common Mistakes:
  • Expecting atoi to ignore leading sign
  • Thinking atoi returns 0 on trailing letters
  • Assuming runtime error due to letters
4. Identify the error in this code snippet using atoi:
char *str = NULL;
int num = atoi(str);
printf("%d", num);
medium
A. Passing NULL pointer to atoi causes undefined behavior
B. Missing header file
C. atoi cannot convert strings with digits
D. No error, code runs fine

Solution

  1. Step 1: Check argument passed to atoi

    The code passes a NULL pointer to atoi, which expects a valid string pointer.
  2. Step 2: Understand consequences of NULL argument

    Passing NULL leads to undefined behavior, often causing a crash or runtime error.
  3. Final Answer:

    Passing NULL pointer to atoi causes undefined behavior -> Option A
  4. Quick Check:

    atoi needs valid string pointer, NULL causes error [OK]
Hint: Never pass NULL to atoi; always check string pointer [OK]
Common Mistakes:
  • Ignoring NULL pointer checks
  • Assuming atoi handles NULL safely
  • Confusing missing header with runtime error
5. You want to convert a string to integer but also detect if the string contains invalid characters after the number. Which approach is best in C?
hard
A. Use atoi and then check the rest of the string manually
B. Use atoi and assume input is always valid
C. Use strtol which provides end pointer to check leftover characters
D. Use printf to convert string to integer

Solution

  1. Step 1: Understand limitation of atoi

    atoi converts initial number but does not provide info about leftover invalid characters.
  2. Step 2: Use strtol for better control

    strtol converts string to long and returns pointer to first invalid character, allowing validation.
  3. Step 3: Choose best approach

    Use strtol which provides end pointer to check leftover characters uses strtol with end pointer to detect invalid trailing characters safely.
  4. Final Answer:

    Use strtol which provides end pointer to check leftover characters -> Option C
  5. Quick Check:

    strtol + end pointer = safe string to int with validation [OK]
Hint: Use strtol with end pointer to detect invalid chars [OK]
Common Mistakes:
  • Relying only on atoi for input validation
  • Ignoring leftover characters after number
  • Using printf incorrectly for conversion
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard