tags:

views:

98

answers:

2
+1  Q: 

c - dynamic memory

Hi everyone out there very first thanks to all of you for providing help. Now i want to know about double pointer. I'm doing code like this:

int main()
{
    int **a;
    a = (int*)malloc(sizeof(*int)*5);
    for (i=0;i<5;i++)
    {
        a[i] = malloc(sizeof(int)*3);
    }
}

Now i dont know if I'm doing it right. How can I put values in this type of array ? Can anybody explain this concept with example ? Thanks in advance.

+4  A: 

Well, you have allocated an array equivalent in size to:

int a[5][3];

So to enter values you just do like this:

a[0][0] = 1234;

Which would put a value into the first column of the first row and

a[4][2] = 9999;

would put another value into the last column of the last row.

Since you are using malloc, you should also loop through a[i] from i = 0 to 4, and free(a[i]); and then free(a); or your program will leak memory.

Amigable Clark Kant
+3  A: 

All right... what you have here, basically, is a pointer-pointer, namely, the adress of an adress. You can use this kind of variable when dealing with arrays.

The first two lines of your code are equivalent to :

int* a[5]; // Declaration of an array of 5 integer pointers (a[0] till a[4]).

A "pure" C code doesn't use variable for the size of an array, so you use the malloc when you want to edit dynamically the size of the array.

Meaning, if in your code, you are not going to change the size of your arrays, you are using a very complex way to achieve a very simple goal. You could just type :

int a[5][3];

But if you do not know the size of your array, you have to use the mallocs (and then, free). What you are doing, basically, is :

  • Declaring an array of array;
  • Allocating the memory for x number of POINTER to integer arrays;
  • For each of these POINTERS, allocating memory for y integers.

Now that you have done this, you can use your arrays normally. For instance :

a[1][0] = 1;

will mean : in the first array [1], the first row [0] is 1.

The only difference with a standard declaration like the one above, without the mallocs, is that since you allocated memory, you'll have to free it. Which is why you don't want to lose your variable a**. At the end of your function, the pointer-to-pointer variable will be destroyed, but not the memory you allocated.

Raveline