I have this program which worked find in my college lab, but when I run it at my home it gives different result
#include <stdio.h>
int main(int argc, char* argv[]) {
const int size=100;
int n, sum=0;
int* A = (int*)malloc( sizeof(int)*size );
for (n=size-1; n>0; n--)
A[n] = n;
for (n=0;n<size; n++)
sum += A[n];
printf ("sum=%d\n", sum);
return 0;
}
I'm expecting 4950 as result but I keep getting different result like 112133223. Why is this happening ?
You are not assigning value to A[0]. As a result of this A[0] will have garbage value which is getting added to sum.
Change
for (n=size-1; n>0; n--)
^^^
to
for (n=size-1; n>=0; n--)
^^^^
Also you need to free the dynamically allocated memory by doing:
free(A);
before you return.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With