S
Seebs
I should know how to do this. I've done it before but I'm just not
getting the right result. I'm getting a huge number when it should be zero.
No, you're getting a huge number when it should be undefined behavior.
#include <stdio.h>
#define __STRICT_ANSI__
int main(void)
{
int i[4], j, k;
k = 0;
for (j = 0; k < 4; ++j)
k = k + i[j];
This loop is almost certainly wrong. Why are you checking "k < 4" rather than
"j < 4"?
But wait, also, i[] is uninitialized.
So.
First, you are iterating through i, adding uninitialized values. You could
get anything.
Secondly, if it happens that j is physically after i, then even if i is all
set to 0s, you will eventually set j to 4. k will still be zero, so you'll
enter the loop, and set k = k + i[4], and i[4] in that case would be j, which
happens to be 4.
But that's speculative, and different machines will give different results.
In general, you have no legitimate expectation of ANYTHING coherent happening.
To fix this:
1. Use "j < 4" as your loop control.
2. Use i[4] = {0} as the initializer. (Elements in the array past those
initialized explicitly will be zero, but this is true only if there is at
least SOME initializer.)
-s