memory allocation for two dimensional array

J

John Hanley

I need to allocate memory dynamically for a two dimensional array. It's
basically a pointer to an array of 2 element arrays: I declared it as long
int ** arr. The number of two element arrays are unknown at compile time.

I am not quite sure if I allocated memory properly for this (I am sure I
didn't).

arr = malloc((sizeof(long int)*2)*number_of_elements)

when I debug it, I have access to arr[0][0], arr[1][0], arr[2][0], etc...
but not arr[0][1]. It tells me it can't access memory which leads me to
believe I don't quite have my memory allocation and/or declaration correct.

I have tried a few different ways, but I obviously haven't found the right
way to do it yet.

Any suggestions?

Thanks a bunch!

John
 
R

Ravi Uday

John Hanley said:
I need to allocate memory dynamically for a two dimensional array. It's
basically a pointer to an array of 2 element arrays: I declared it as long
int ** arr. The number of two element arrays are unknown at compile time.

I am not quite sure if I allocated memory properly for this (I am sure I
didn't).

arr = malloc((sizeof(long int)*2)*number_of_elements)
Have you tried looking into C-FAQ section.
Allocating 2D arrays are nicely discussed there

- Ravi
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top