Even if you fix the first bug, as I suggested, there would still be a problem if nballs was anything other than 1. Let's use 3 for this example. The first time through the loop, i is 0, you allocate an array of 3 balls (ball[0], ball[1] and ball[2]). You initialize ball[i], which is ball[0]. Then i is incremented and becomes 1. You then allocate a new array of 3 balls, losing the old one. i is 1, so when you initialize ball[i], you initialize ball[1], but not ball[0] or ball[2]. Remember, it's a new array (you called malloc again), and
this array has a ball[0] that is uninitialized. i is incremented again, and is 2. Similarly, you allocate a new array, now you've lost the first two. You initialize ball[i], which is ball[2]. ball[0] and ball[1] in the new array are uninitialized. Any time you use ball[0], you're using random garbage values, because it's not initialized. Now, we jump down to this line:
Code:
ballmatxpos[m][1]=ball[0].xpos;
Now you've assigned bad values to ballmatxpos[m][1], and on this line:
Code:
fprintf( pFile2, " %3.4lf \n", ballmatxpos[m][1]);
You will be printing those incorrect values to your file.
The original malloc call, outside the loop is fine. If nballs is more than 1, it will allocate space for more than 1 sphere. That is the point of the
nballs * part of the malloc call. This always allocates one sphere object:
Code:
ball = malloc(sizeof(sphere));
This always allocates nballs number of sphere objects:
Code:
ball = malloc(nballs * sizeof(sphere));
Use the second one, it will always be correct. Then, make sure
all your loops that access that array,
start with i = 0; and use i < nballs; as a stopping condition (again, note just a plain "less than", not "less than or equal to").