Value of array element changes itself during loop in c language -
i have written simple code in c. problem element value changing during loop, though there no such command. elements calculated in first loop become 0 after loop ends. elements calculated in 2nd or higher numbered loop show correct values, don't become 0 (obviously). why did elements become zero? mistake?
i have printed value of u(1,0)
every time.
#include <stdio.h> /* standard library of input , output */ #include <complex.h> /* standard library of complex numbers */ #include <math.h> #include <string.h> #include <stdlib.h> #define pi 3.141592 int main() { // declaration variables // integers int n = 2, nx = n, ny = n, i, j; // important give n-1 n double x[nx], y[ny], lengthx = 1.0, lengthy = 1.0; double complex u[nx][ny]; // x direction (i = 0; <= nx; i++) { x[i] = (double)i / (nx + 1) * lengthx; //printf("x coordi %.15f \n", x[i]); } // y direction (j = 0; j <= ny; j++) { y[j] = (double)j / (ny + 1) * lengthy; //printf("x coordi %.15f \n", x[i]); } (j = 0; j <= ny; j++) { (i = 0; <= nx; i++) { printf("x coordi %.15f \n", x[i]); u[i][j] = sin(2.0 * pi * x[i]) * cos(2.0 * pi * y[j]); // x[i] = (double)i / (nx + 1) * lengthx; printf("u (i,j) = (%i,%i)\t%.15f\t%f\t%f\n", i, j, u[i][j], x[i], y[j]); //correct printf("u (i,j) = (%i,%i)\t element u[1][0] %.15f \n\n\n", i, j, u[1][0]); } printf("\n\n\n end of inside loop (i,j)=(%i,%i) u(1,0) \t%.15f \n", i, j, u[1][0]); } printf("\n\n u %i\t%i\t%.15f \n\n", i, j, u[1][0]); printf("\n\n\n\n why u(1,0) value become 0 in last loop ???????\n"); printf("\n\n\n\n not u(1,0) value become zero, u(:,0) in last loop became 0 !\n"); // return 0; }
if understand question x[0]
, y[0]
zeros , other indexes ok. in code, there bugs. 1. for ( j=0; j<=ny; j++ )
, for ( i=0; i<=nx; i++ )
accessing memory not allocated program , read-only, error segfault. 2. x[i]=(double)i/(nx+1)*lengthx;
start calculation when j , initialized 0 , why 0 @ first index.
for ( i=1; i<=nx; i++ ) { x[i-1]=(double)i/(nx+1)*lengthx; //printf("x coordi %.15f \n", x[i]); } // y direction ( j=1; j<=ny; j++ ) { y[j-1]=(double)j/(ny+1)*lengthy; //printf("x coordi %.15f \n", x[i]); }
Comments
Post a Comment