• C

Adding integer data with single pointer

If you have an array of integers, is it legal (or recommended) to get a sum by iterating through the array with a pointer, and adding the value pointed to by the next pointer, to the value pointed to by the current pointer?  Like this:

      int* ptr = (int*) malloc(3 * sizeof(int));

      ptr[0] = 66;
      ptr[1] = 50;
      ptr[2] = 1000;

      int* sum = ptr;
      for (unsigned i = 0; i < 2; ++i)
            *sum += *(++sum);


This works, but I wonder if it's ANSI compliant, or if it is even a good idea.  What sort of assembly code would this generate?  Would it be more efficient than using a temporary value and incrementing that?
Who is Participating?
sunnycoderConnect With a Mentor Commented:
oops .. I posted too soon ... ++sum modifies the pointer and += modifies the *sum, so this should be fine ... note that you are chaging the values in your array to get cumulative sum
Hi chsalvia,

No it would not work ...
*sum += *(++sum);
This modifies the value *sum more than once between two sequence points ...

chsalviaAuthor Commented:
I see.  So you'd need to do:

      int sum = 0;
      for (unsigned i = 0; i < 3; ++i)
            sum += *(ptr++);
yes, that would not modify the contents of the array and yet give you the sum.
*sum += *(++sum); modifies sum only once, but it violates the requirement that the prior value shall be read only to determine the value to be stored, so it's still illegal
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.