Mike Travis
Mike Travis

Reputation: 13

Int pointers having weird behavior in C

void main(){
  int digits[21]; //this was initialized so that every element is 0 by looping over every element and setting it to 0
  char input[20];
  scanf("%s", input);
  parseDigits(digits, input);
}

void parseDigits(int* digits, char *string){
  char *end = string + strlen(string) -1;
  int i;
  for (i = 0; i < strlen(string) - 1; i++, end--){
    int *digit = digits + i;
    printf("%d", *digit);
    *digit += charToDigit(*end);
    if (*digit >= 10){ //carry one
      *digit -= 10;
      digit++;
      *digit += 1;
    }
  }
}

Prints an excessively large integer, instead of 0, which is the expected output. I don't understand since

digits + i

should still be within the range of the array.

Upvotes: 0

Views: 92

Answers (1)

tdao
tdao

Reputation: 17678

There can be other issues, but from first glance you have not initialized your array properly, which should have been done like:

int digits[21] = { 0 };

Upvotes: 1

Related Questions