I'm writing a simulation in population genetics and am having a problem setting up the initial population. The problem boils down to this...

int test[1][1][1];
test[0][0][1]=1;
test[1][0][0]=2;
printf("test: %d\n",test[0][0][1]);

Why does this print 2? I feel like it should print 1. I've searched forums for an answer, but haven't been able to find one. If there's one out there, please point me to it. Thank you.

If you're interested in the background, I'm setting up a 3D array to represent a population. The first index contains the number of the individual, the second index contains the loci, and the third index contains the allele (only 2, since these are diploid organisms). All the individuals should initially have one of each allele, so I run

//Set up initial population
	for (i=0;i<N;i++){
		for (j=0;j<loci;j++){
			population[i][j][0]=-1;
			population[i][j][1]=1;
		}
	}

(loci is set to 1 for testing purposes) but only the last individual has both -1 and 1. Individuals 0 to N-2 have -1 and -1, and this is a problem.

Try changing your array to..

int test[2][2][2];

Try running this code below

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

int test[1][1][1];
int test2[2][2][2];

int main()
{
	fprintf(stdout, "array elements->%lu\n", sizeof(test)/sizeof(int));
	fprintf(stdout, "array elements->%lu\n", sizeof(test2)/sizeof(int));
	return 0;
}

You made an array with only 1 row, 1 column, and 1 depth.

Since arrays in C always begin with subscript 0, trying to refer to [1] in any dimension, is junk - you're out of bounds. ;)

Thanks guys, you solved it. I thought [1] meant it would include space at 0 and 1. I guess I should mark it [2]. I'm new to C. I normally use Matlab, but I hear that C runs much faster.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.