# Dynamic Memory Assignment for a 2D Triangular Matrix

I want to initialize a 2-D array such that, every row has different number of elements. Morever, the number of elements of a row depends on the number of elements in it's previous row. For instance, the function governing the number of elements in a row be:

``````Rows(N)= 2*Rows(N-1) +1
```
```

where, Rows(N) is the number of cells in the Nth row.

The problem can be solved easily, if i can find the size of an array. for instance, I tried:

``````int A[10];
```
```

then it's size is `sizeof(A)/sizeof(int)`, it gives me 10. (correct)

But if I allocate memory like:

``````int *A;
A=(int *)malloc(sizeof(int)*10);
```
```

and then check the value of `sizeof(A)/sizeof(int)`, it gives me 1.(wrong) So, this approach doesn't work here.

Can anybody help me on this one.

While you can access dynamic memory like an array in C, it has different semantics. When you ask for `sizeof(A)/sizeof(int)`, you're actually asking `sizeof(int *)/sizeof(int)`. Since those two quantities are equal (e.g. both 32-bit), the answer is `1`.

With dynamic memory the length of the "array" is not known at compile-time, so you need to explicitly store it in a separate variable. Alternatively, you could wrap the memory and its length in a struct (or a pointer to the struct) around as a single variable.