carray-indexing

Question regarding C loops


I'm not exactly sure why this isn't returning what it should be, perhaps one of you could help me out. I have the following for loop in C:

for (i=0; i<nrow; i++) {
    dat[k]=l.0;
    k++;
}

Now, you would think that this would set all values of dat (of which there are nrow values) to 1.0; Instead, it is being set to 0. The program compiles fine and everything goes smoothly. The memory is properly allocated and dat is defined as a double.

Is there a reason this is yielding 0? I'm guessing the 0 is coming from the initialization of the dat variable (since I used calloc for memory allocation, which supposedly initializes variables to 0 (but not always)).

EDIT: Please note that there is a specific reason (this is important) that I'm not defining it as dat[i]. Additionally. k was defined as an integer and was initialized to 0.

EDIT 2: Below is the entire code:

#include "stdio.h"
#include "stdlib.h"
#define NCH 81

// Generate swap-mode data for bonds for input.conf file

int main() 
{
    int i,j,k;
    int **dat2;
    double *dat;

    int ns = 500;

    int nrow = NCH*(ns-1);

    dat = (double*) calloc(nrow, sizeof(double));
    dat2 = (int**) calloc(nrow,sizeof(int*));

    /*for (i=0; i<nrow; i++) {
        dat2[i] = (int*) calloc(2, sizeof(int));
        for (j=0; j<2; j++)
            dat2[i][j] = 0;
    }*/

    k=0;

    printf("\nBreakpoint\n");

    /*for (i=0; i<81; i++) {
        for (j=0; j<250; j++) {
            dat[k] = j+1;
            k++;
        }

        for (j=251; j>1; j++) {
            dat[k] = j-1;
            k++;
        }
    }*/

    FILE *inp;
    inp = fopen("input.out", "w");

    for (i=0; i<nrow; i++) {
        dat[k]=1.0;
        k++;
    }

    //fprintf(inp, "%lf\n", dat[i]);

    printf("%d", dat[nrow]);
    printf("\nDone\n");
    fclose(inp);

    return 0;
}

Thanks! Amit


Solution

  • printf("%d", dat[nrow]);
    

    is not valid, because the nrow'th element of dat doesn't exist.