2d pointers, memset or how to initialise?

Status
Not open for further replies.

legolas

Padawan
hi,

suppose i have

#....

main()
{
int n=6;(which means i am to generate a 6*6 matrix)
int **a;

and some how i allocated the memory required for 6*6 to the pointer a....

now, how do i initialise the elements of pointer a to "0" so that i can start accessing them as arrays without any junk values... coz, in my program some values r untouched and if i initialise to "0", it wud be fine, with junk its jus disappointing... i hav heard of memset command for 1d pointers, is it possible ot initialise 2d pointers using the same? thk u.

/legolas
 

gtoX

Broken In
Well, it depends on the reqd. speed of program you are creating.

You could create an initialisation portion inside the main() fnx., inside a for loop.
If it is time-critical, I suggest you use assembly codes in place of the for loop if your compiler supports it.

i think memset also works, because all it requires is the starting address(in your case, the int 'a'), and the total size of the array(6*6 = 36), irrespective of the dimension of the array. However, I haven't personally done that. You could try it out.
 

aadipa

Padawan
In reality, you will not need pointers to pointers (2D pointers) to store a matrix, a simple pointer will do, all you need is a mapping function.

Say I want to store a[6][6] in *p, then a[j] is *(p+(i*columes)+j)

A real use of pointer to pointer is when you need to exchange the rows in the matrix, or when you have to store array of different lengths and need a same mapping function.

In that case
Code:
int **p;

p = (**int) malloc(sizeof(int *)*ROWS);
for(i=0; i<ROWS; i++) 
{
    *(p+i) = (*int) calloc(sizeof(int), COLS); // calloc will set all to 0
}

*(*(p+2)+4) = 5;  // Same as  a[2][4] = 5

Here the mapping function becomes a[j] = *(*(p+i)+j)


I have not checked the code as I don't have any C compiler on my desk right now, but I think it is correct. Just try and reply. i hope that was what you wanted.
 
OP
L

legolas

Padawan
@aadipa,

thks for the initialisation help, but i needed 2d pointers coz, i am using arrays of size 1000*1000 or more even and so i cant declare them static... the stack memory gts exceeded, so i got 2 make sure that i free them asa their need is over.. and moreover, with pointers, the stack memory usage is also better... i tried a different initialisation thou, it worked, and i am sure the initialisation i gave wud work either, coz i understood a lots abt these owing to that implementation.. thks for ur help. :)

/legolas
 
Status
Not open for further replies.
Top Bottom