I'm very inexperienced with C and have to use it for a piece of coursework exploring heat transfer.
I'm getting all sorts of errors with the (0xC0000005) return code. I'm aware that this is an attempt to access memory out of bounds and that I'm probably failing to allocate memory properly somewhere but I haven't been able to figure it out.
Any idea what needs changing?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
/* constant alpha squared, the area of the domain */
const float alphSqrd = 0.01;
const float deltX, deltY = 0.0002;
const float timeStep = 0.0000009;
const int maxTimeSteps = 1000;
int h, i, j;
/* 2D Array of Temperature Values */
float T [500][500];
float dTdt;
/* initialise temperature values */
printf("Initialising 2D array...\n");
for (i=0; i<500; i++){
for (j=0; j<500; j++){
if (150<=i && i<350 && 150<=j && j<350){
T[i][j] = 50;
} else {
T[i][j] = 20;
}
}
}
printf("Updating values...\n");
for (h=0; h<maxTimeSteps; h++){
for (i=0; i<500; i++){
for (j=0; j<500; j++){
dTdt = alphSqrd*(((T[i+1][j]-2*T[i][j]+T[i-1][j])/(deltX*deltX))+((T[i][j+1]-2*T[i][j]+T[i][j-1])/(deltY*deltY)));
T[i][j] = T[i][j] + dTdt * timeStep;
printf("%f ",T[i][j]);
}
printf("\n");
}
}
return 0;
}
During your dTdt
calculation you are using T[i-1][j]
and T[i-1][j]
. If i is maximal (0 or 500) this exceeds the array limits. The same holds for j.
Thus, you use uninitialised memory. You need to loop form 1
to 499
and treat the boundary differently depending on the problem you are trying to solve.
Although that's not the problem you're describing, one issue is that you're not initializing deltX
. Instead of this
const float deltX, deltY = 0.0002;
you want
const float deltX = 0.0002 , deltY = 0.0002;
Aside from that, you have an out of range issue. If you're going to access index i - 1
and i + 1
, you can't loop from 0
to 499
on an array of 500
elements.
It works for me if I adjust the loops like this:
for (i = 1; i < 499; i++) {
for (j = 1; j < 499; j++) {
Firstly adjust the loop min and max values;
for (i=1; i<499; i++){
for (j=1; j<499; j++){
And you should make comment line to printf()
. stdout
takes much time in the loop.
for (h=0; h<maxTimeSteps; h++){
for (i=1; i<499; i++){
for (j=1; j<499; j++){
dTdt = alphSqrd*(((T[i+1][j]-2*T[i][j]+T[i-1][j])/(deltX*deltX))+((T[i][j+1]-2*T[i][j]+T[i][j-1])/(deltY*deltY)));
T[i][j] = T[i][j] + dTdt * timeStep;
//printf("%f ",T[i][j]);
}
//printf("\n");
}
}
I compiled this code on my virtual Linux and it took nearly 3 seconds. enter image description here
User contributions licensed under CC BY-SA 3.0