[Solved] Problem multidimentional array

Posted By: djfeeler

[Solved] Problem multidimentional array - 06/03/14 04:10

Hello !

I have problem with array mutidimentionnal. When i do SIZE_WIDTH 1 and SIZE_HEIGHT 5 the data is well passed, it gives good 1, 2, 3, 4, 5. But when I enlarged the array with SIZE_WIDTH 2 and SIZE_HEIGHT 5, it no longer reads the data it displays anything . Tell me what can be my problem.

Code:
// test array multidimentional

#include <acknex.h>
#include <default.c>

#define SIZE_WIDTH 1
#define SIZE_HEIGHT 5

void loadLevel(var *level);

void main()
{
	
	// Simple array
	
	var tab2[SIZE_WIDTH][SIZE_HEIGHT] = {0}, i = 0, j = 0;
	
	// Double dynamic array allocation
	
	/*var **tab2 = NULL, i = 0, j = 0;
	
	tab2 = sys_malloc(SIZE_WIDTH * sizeof(var));
	
	for(i = 0; i < 5;i++)
		tab2[i] = sys_malloc(SIZE_HEIGHT * sizeof(var));
		
	if(tab2 == NULL)
	{
		printf("unallocated memory");
		sys_exit(NULL);
	}
		
	for(i = 0; i < SIZE_WIDTH;i++)
	{
		for(j = 0; j < SIZE_HEIGHT;j++)
		{
			tab2[i + j] = 0;
		}
	}*/
		
	tab2[0 + 0] = 1;
	tab2[0 + 1] = 2;
	tab2[0 + 2] = 3;
	tab2[0 + 3] = 4;
	tab2[0 + 4] = 5;
	
/*tab2[1 + 0] = 6;
	tab2[1 + 1] = 7;
	tab2[1 + 2] = 8;
	tab2[1 + 3] = 9;
	tab2[1 + 4] = 10;*/
	
	for(i = 0; i < SIZE_WIDTH;i++)
	{
		for(j = 0; j < SIZE_HEIGHT;j++)
		{
			printf("%d",(long)tab2[i + j]);
		}
	}
	
	//loadLevel(tab2);
	
	/*for(i = 0; i < 5;i++)
	{
		for(j = 0; j < 5;j++)
		{
			printf("%d",(long)tab2[i + j]);
		}
	}*/
	
	//	sys_free(tab2);
}


void loadLevel(var *level)
{
	level[0 + 0] = 1;
	level[0 + 1] = 2;
	level[0 + 2] = 3;
	level[0 + 3] = 4;
	level[0 + 4] = 5;
	
	/*level[1 + 0] = 6;
	level[1 + 1] = 7;
	level[1 + 2] = 8;
	level[1 + 3] = 9;
	level[1 + 4] = 10;*/
}




Thanks in advance Djfeeler
Posted By: Superku

Re: Problem multidimentional array - 06/03/14 04:18

Remove:
var tab2[SIZE_WIDTH][SIZE_HEIGHT] = {0}

Replace the whole memory allocation with:
var *tab2 = sys_malloc(SIZE_WIDTH * SIZE_HEIGHT * sizeof(var));

The first initialization block is fine but the (commented) second one is obviously wrong, you are just writing over entry "1 + 0 = 1 = 0 + 1" and so on. What you wanted to do is the following:
tab2[1*SIZE_HEIGHT + 0] = 6;
...

Btw. a for loop would be appropriate here:
for(i = 0; i < 5; i++)
{
tab2[0*SIZE_HEIGHT + i] = i;
tab2[1*SIZE_HEIGHT + i] = i+5;
}
Posted By: djfeeler

Re: Problem multidimentional array - 06/03/14 05:11

Thanks for your help. I just understand how it worked.
© 2024 lite-C Forums