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.
You never assign a value to A[0] - the first loop ends to quickly. However you do include this unassigned value in the summation.
A[0]
is undefined:
for (n=size-1; n>0; n--)
should be
for (n=size-1; n>=0; n--)
Just because you didn't put any value in first element, you had garbage there. thus, some random number in sum.
#include <stdio.h>
#include<stdlib.h> //for malloc
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--) //you forgot '='
A[n] = n;
for (n=0;n<size; n++)
sum += A[n];
printf ("sum=%d\n", sum);
return 0;
}
it worked fine for me. I executed it using GCC. this is the program i ran:
#include <stdio.h>
#include <malloc.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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.