Sairam D Sairam D - 5 months ago 14
C++ Question

Turbo C++ and GCC compiler produces different results during pointer incrementation?

The below program is used to calculate the sum of the floating point numbers in an array.

I just modified it using pointer concept by assigning the base address of the array 'a' to the pointer variable 'p' and then incrementing the pointer variable to calculate the sum of the array.

int main()
float a[5],*p,sum=0.0;
int i;
return 0;

But while compiling this program using a GCC compiler the sum of the array just gets doubled. Why this happens??

NOTE: This problem occurs only with GCC compiler, Turbo C++ produces the correct result.

EDIT: As you guys say that p is not guaranteed to be
at the end of the array then how come one compiler(TURBO C++) can able to produce the correct result and the other one (GCC) just doubles it instead of printing some garbage values.


This is the wrong loop condition: *p!='\0'

This is equivalent to *p != 0.0f, but your array is not terminated this way. The loop will run too long and the program will try to access beyond the bounds of the array, which is an error. You want i < 5 instead. Here is a fixed version of your loop.

for (i = 0, p = a; i < 5; i++, p++) {
    sum += *p;

Any time your code has an error of this kind in it, there is a chance that the error will manifest differently depending on the compiler or settings.

Since this is C++, you can write the array this way instead:

for (auto item : a) {
    sum += item;