Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c loop stops when array value is zero not null

Tags:

int findMax(int*sums){
  int t = 0;
  int max = sums[0];
  while (sums[t] != '\0'){
    printf("current max: %d %d\n", max, sums[t]);
    if (sums[t] > max ){
      max = sums[t];
    }
    t ++;
  }
  return max;
}

This outputs:

current max: 7 7
current max: 7 4
current max: 7 2

And its ignoring the rest of the list, sums. I think this is because the next element in sums is 0. But I can't see why it would treat 0 as '\0' (null).

like image 570
Karen McCulloch Avatar asked Jul 09 '16 19:07

Karen McCulloch


1 Answers

sums is an array of integers (technically a pointer to integer). '\0' (the null byte) and 0 are the same value, so your loop will stop when it encounters a 0. There is no such thing as a null value as far as integers are concerned. The term "null" is used to refer to the value NULL, which is a pointer usually with the value 0 (i.e., a pointer that doesn't point to anything), and also the null (0) byte, such as the one that occurs at the end of a null-terminated string.

like image 65
Andy Schweig Avatar answered Sep 28 '22 03:09

Andy Schweig