r3k0j
r3k0j

Reputation: 187

why do i not get the correct value for sum?

#include <stdio.h>
#include <stdlib.h>

int sumArray(int* p);

int main(){

    int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, sum;
    int* p = array;
    sum = printf("The sum of the array is: %d", sumArray(p));
    return 0;
}

int sumArray(int* p){

    int sum = 0;
    while(*p){
        sum += *p;
        p++;
    }
    return sum;
}

when i run this code i get a 6-digit value for sum, which looks more like an address. so what exactly am i doing wrong here?

Upvotes: 1

Views: 84

Answers (1)

Govind Parmar
Govind Parmar

Reputation: 21542

while(*p) is a pretty idiomatic way of processing character strings in C because they have the useful property of being null-terminated. Once the null terminator (character with numeric value of 0) is reached, *p is 0 and the loop ends.

Your array does not have this property so while(*p) is true for the entire length of your array, then it goes out of bounds, which is undefined behavior.

Your options are:

  1. Pass the size along with the array, and use int i = 0; while (i < LENGTH){} or more idiomatically for(int i = 0; i < LENGTH; i++)
  2. Use a designated sentinel value to indicate the end of the array and use while (*p != SENTINEL)

Former option is the least hassle and doesn't require you to designate an arbitrary int as a magic number.

Upvotes: 1

Related Questions