Software > Software

matrices in C, undetermined size?

(1/3) > >>

Admin:
Is there a way to create matrices in C of undetermined size? I know its possible in some languages, but Im thinking no for C . . .

ed1380:

razvanc_roro:
I think you can declare a matrice of undetermined size and border it iterativelly:

you can initilize a 1x1 matrice (a[1][1]="give value/initilize") and then, when ever you need you can choose by border it with 1 column or one row or both...
if there was a matrice a[m][n] by now,
if <condition> then for (j=1,n+1) and (i=1,m+1) a[m+1][j]="give value/initilize" , a[.i][n+1]="give value/initilize" (this is for both row and column). You get it...

PS: 1) Hope that I understood what you wanted to say :D
      2) [.1] > the "." is for the unITALIC code of the editor :)
Cheers!

rgcustodio:
Nope you can't make a matrix of undetermined length in C at compile time. BUT, you can dynamically allocate memory during runtime! You will have to deal with pointers and dynamic memory allocation. The big issue is that MCUs (like the AVR) do not have large RAM (most have 1024 bytes only). I think avrlibc supports malloc/free APIs but I haven't personally used them.


--- Quote from: razvanc_roro on June 23, 2007, 03:51:10 PM ---I think you can declare a matrice of undetermined size and border it iterativelly:

you can initilize a 1x1 matrice (a[1][1]="give value/initilize") and then, when ever you need you can choose by border it with 1 column or one row or both...

--- End quote ---

A user can not control the placement of a variable in memory. So if you have several variables and you implement the above procedure you risk running over memory (buffer overrun) that is supposed to be owned by another variable. To properly utilize the above technique the user must be able to place the matrix at a memory location where the user is assured that it'll not hit used memory locations.

For roro's suggestion to work one will have to use a big array and a pointer. N x N matrices are just one big chunk of contiguous memory. One can simulate an N x N matrix by using the big array. And using pointer arithmetic to access the correct memory location. One can write functions to simplify these operations.


--- Code: ---int myarray[100];
int *p = NULL;

/* simulate a 2 x 50 matrix */
// access first 50 bytes
p = myarray[0]; // like saying n[0][0]
*p = 100;
p = myarray[1]; // like saying n[0][1]
*p = 101;
p = myarray[48]; // like saying n[0][48]
*p = 148;

// access second 50 bytes
p = myarray[50]; // like saying n[1][0]
*p = 100;
p = myarray[51]; // like saying n[1][1]
*p = 101;

--- End code ---

It is not a matrix of undetermined size.

Admin:
So the reason I asked is that Im doing robot mapping in an unknown area and just wanted my map to get bigger only when it needed to.

I guess it might be easier to just define a map large enough to fill the rest of my unused memory instead . . .

Navigation

[0] Message Index

[#] Next page

Go to full version