Search code examples
calgorithmintatoi

Implementing atoi - Segmentation Fault when incrementing variable j


The C program starts by storing an string input that is a number: "134" and stores each char into a char array. Then it starts from the last char of the array "4" and then multiplies it by 10^0, then the next element multiplied by 10^1 and so on...

Ex: sum = (4* 10^0) + (3 * 10^1) + (1 * 10^2)

I'm not allowed to use the built in pow library so I implemented one myself. The program works only when an input string is something in the ones or tens so like: 5 or 56 or 28, etc. but doesn't work for any number in the hundreds or higher. (I started receiving seg faults the moment I added j++)

#include <stdio.h>
int pow(int, int);
int i;
int result;
#define SIZE 10
char input[SIZE];
int j = 0;

int main(){
    printf("Enter a word of positive number or quit: ");
    scanf("%s", input);
    int sum = 0;
    for(i = strlen(input)-1; i >= 0; i--){
        printf("pow: %d\n", (input[i] - '0') * pow(10, j));
        sum = sum + ((input[i] - '0') * pow(10,j));
        printf("sum: %d\n", sum);
        j++;
        printf("j: %d\n", j);
    }
    printf("%d\n", sum); 
}

int pow(int base, int exponent){
    if(exponent == 0) return 1;
    if(exponent == 1) return base;
    result = 1;
    for(i = 0; i < exponent; i++){
        result = result * base;
    }
    return result;
}

Solution

  • You have declared i as a global variable. It is then used as an iterator both in main() and pow(), which is not desired. This can be fixed by making the iterator local to the scope of the loop, as

    for (int i = strlen(input)-1; i >= 0; i--)
    

    and

    for (int i = 0; i < exponent; i++)