Search code examples
cfunctiondynamic-memory-allocation

Why a variable is not storing the value?


In this problem, there is a cube of size 200 x 200 x 320 Now I want to allocate a variable "isn" for all the points in the lattice nodes with 0 and 1. The value of the "isn" parameter for the lattice nodes from 85-115 in x direction, 85-115 in y direction and 240-270 in z direction is allocated as 1 and rest of the nodes as 0. After the allocation when I try to print the "isn" value for the node (100,100,255), it should give result as 1. But it is giving 0.

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>

const int nx=200, ny=200, nz=320;

int getindex1(int i, int j, int k)
{
    int c = (i*(ny+2)+j)*(nx+2)+k;
    return c;
}

int main()
{
    int i, j, k, ia, ja, ka;
    int *isn;

    //******Dynamic Memory Allocation
    isn = (int*) malloc (((nx+2)*(ny+2)*(nz+2)) * sizeof(int));

    for(i=0;i<=nx+1;i++)
    {
     for(j=0;j<=ny+1;j++)
         { 
           for(k=0;k<=nz+1;k++)
           {
            isn[getindex1(i,j,k)]=0;    
           }    
        }   
    }

    for(i=0;i<=nx+1;i++){
            for(j=0;j<=ny+1;j++){
                for(k=0;k<=nz+1;k++){
                    isn[getindex1(i,j,k)]=0;
                    if(i>=85 && i<=115 && j>=85 && j<=115 && k>=240 && k<=270)
                    {
                        isn[getindex1(i,j,k)]=1;
                        printf("getindex1(%d,%d,%d)=%d\tisn=%d\n",i,j,k,getindex1(i,j,k),isn[getindex1(i,j,k)]);
                    }   
                    
                    if(i==100 && j==100 && k==255)
                    {
                        printf("\n\ngetindex1(100,100,255)=%d\tisn=%d\n\n",getindex1(100,100,255),isn[getindex1(100,100,255)]);
                    }       
                }
            }
        } 


printf("\n\ngetindex1(100,100,255)=%d\tisn=%d\n\n",getindex1(100,100,255),isn[getindex1(100,100,255)]);
        
    return 0;
}

Solution

  • You have mixed up the dimensions, the index calculation should be

    (i * (ny + 2) + j) * (nz + 2) + k
    

    Your logic will be easier to manage if you introduce variables which stands for the dimensions of the tensor, like this:

    int isnLayers, isnRows, isnCols;
    
    isnLayers = nx + 2;
    isnRows = ny + 2;
    isnCols = nz + 2;
    
    isn = malloc(sizeof (*isn) * isnLayers * isnRows * isnCols);
    
    for (i = 0; i < isnLayers; i++) {
        for (j = 0; j <  isnRows; j++) {
            for (k = 0; k < isnCols; k++) {
                ...
            }
        }
    }