数组元素的值在c语言循环期间自行更改

时间:2017-08-20 08:37:43

标签: c arrays loops for-loop nested-loops

我在C中编写了一些简单的代码。问题是元素值在循环期间发生了变化,即使没有这样的命令。循环结束后,在第一个循环中计算的所有元素都变为零。但是在第二个或更多编号的循环中计算的元素显示正确的值,它们不会变为零(显然)。那么为什么这些元素变成零?错误在哪里?

我每次都打印u(1,0)的值。

#include <stdio.h>      /* Standard Library of Input and 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 FOR N
    double x[Nx], y[Ny], lengthX = 1.0, lengthY = 1.0;
    double complex u[Nx][Ny];   

    // FOR X DIRECTION
    for (i = 0; i <= Nx; i++) {
        x[i] = (double)i / (Nx + 1) * lengthX;
        //printf("x coordi is %.15f \n", x[i]);
    }

    // FOR Y DIRECTION
    for (j = 0; j <= Ny; j++) {
        y[j] = (double)j / (Ny + 1) * lengthY;
        //printf("x coordi is %.15f \n", x[i]);
    }

    for (j = 0; j <= Ny; j++) {
        for (i = 0; i <= Nx; i++) {
            printf("x coordi is %.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 is (i,j) = (%i,%i)\t%.15f\t%f\t%f\n", i, j, u[i][j], x[i], y[j]); //correct
            printf("u is (i,j) = (%i,%i)\t element u[1][0] is %.15f \n\n\n", i, j, u[1][0]); 
        }
        printf("\n\n\n End of inside loop (i,j)=(%i,%i)  u(1,0) is \t%.15f \n", i, j, u[1][0]); 
    }
    printf("\n\n u is %i\t%i\t%.15f \n\n", i, j, u[1][0]); 

    printf("\n\n\n\n Why u(1,0) value become zero in the last loop ???????\n");
printf("\n\n\n\n Not only u(1,0) value become zero, but all u(:,0) in the last loop became zero !\n");
    //
    return 0;
}

2 个答案:

答案 0 :(得分:0)

如果我理解您的问题x[0]y[0]是零并且所有其他索引都可以。所以在你的代码中,有一些错误。 1. for ( j=0; j<=Ny; j++ )for ( i=0; i<=Nx; i++ )您正在访问未分配给您的内存并且可能是只读的内存,您可能会收到错误SEGFAULT。 2. x[i]=(double)i/(Nx+1)*lengthX;当j和i初始化为零时开始计算,这就是为什么在第一个索引处得到零的原因。

for ( i=1; i<=Nx; i++ ) {
        x[i-1]=(double)i/(Nx+1)*lengthX;
        //printf("x coordi is %.15f \n", x[i]);
}

// FOR Y DIRECTION

for ( j=1; j<=Ny; j++ ) 
{
        y[j-1]=(double)j/(Ny+1)*lengthY;
        //printf("x coordi is %.15f \n", x[i]);
}

答案 1 :(得分:0)

数组溢出其范围。就像上面一样,你应该纠正循环: 将for ( i=0; i<=Nx; i++ )替换为for(i = 0; i < Nx; i++),因为只有Nx元素,但您再设置一个