Problem with pointers in C

So, I have this code:

#include <stdio.h>
int arraySum (int *a, int n);
int main(void){
    int values[3] = {1, 2, 3};
    printf("The sum is %i\n", arraySum(values, 3));
    return 0;
}
int arraySum(int *a, int n){
    int sum = 0;
    int arrayEnd = *a + n;
    for ( ; *a < arrayEnd; *a++)
        sum += *a;
    return sum;
}

For some reason, it outputs this:

roman@lmde64 ~/Dropbox/Practice $ gcc practice.c 
roman@lmde64 ~/Dropbox/Practice $ ./a.out
The sum is -421028781
roman@lmde64 ~/Dropbox/Practice $ ./a.out
The sum is -362865581
roman@lmde64 ~/Dropbox/Practice $ ./a.out
The sum is -1046881197
roman@lmde64 ~/Dropbox/Practice $ ./a.out
The sum is 6
roman@lmde64 ~/Dropbox/Practice $ ./a.out
The sum is 6

Why do weird numbers and the correct answer sometimes appear? What am I doing wrong? Thanks for any help.

+5
source share
5 answers

You arraySum()are confused when you use it aas a pointer and when you look for it to get what it points to. When you calculate the limits of a loop, etc., you want to work with the pointer itself:

int arraySum(int *a, int n){
    int sum = 0;
    int *arrayEnd = a + n;
    for ( ; a < arrayEnd; a++)
        sum += *a;
    return sum;
}
+14
source

You want to iterate over the array:

int arraySum(int *a, int n){
    int sum = 0;
    int * arrayEnd = a + n; // arrayEnd points to the first element after your array a
    for ( ; a != arrayEnd; ++a)  // Iterate over the array until you reach arrayEnd
        sum += *a; // Dereference the pointer to current array element in order to retrieve a value
    return sum;
}
+2
source
  • *a++ *(a++); *
  • arrayEnd *a + 3 1 + 3, 4
  • for . undefined
  • " - , ! \n"
+1
int arraySum(int *a, int n) {
   int sum = 0;
   for (int i = 0; i < n; ++i)
      sum += a[i];
   return sum;
}

int arraySum(int *a, int n) {
   int sum = 0;
   for (int i = 0; i < n; ++i)
      sum += *a++;
   return sum;
}
+1

  • *a + n 1+3 = 4
  • for , *a, 4.
  • *a 4, sum.
  • After 3 iterations, apoints to values[2]which is equal 3. Later, when aincremented, it points to an address outside value[2]- this address can contain any garbage value. If the garbage value is less 4, it will calculate sum. This behavior continues until a larger value appears 4. Hence, the value is sumsometimes 6or another meaning of garbage
+1
source

All Articles