- Mar 18, 2003
- 5,513
- 0
- 0
So I did a few semesters in C a couple of years ago and had the whole pointer/array thing down reasonably well. Mostly that int * foo is equivalent to int foo[].
I probably had done some 2d arrays (on the stack at least) and the concept that it's just one chunk of memory with a complex index is clear enough. I'm doing some stuff in c again needing to dynamically allocate a 2d array of integers so I assumed that you could use a double pointer just like a 2d array, but of course I'm wrong.
After reading a bit and thinking I get it that an int ** needs a series of seperately allocated chunks because the first array is an array of pointers. Am I correct in my understanding that you then access it with the same syntax as a 2d array on the stack and the compiler will figure out whether or not to use the indirection to follow your indices? (see code eg #1
Also, is it not possible to malloc a single block and use a cast to trick the compiler into accessing it like a stack 2d array? See code eg #2 for how I picture this (it's not working, obviously).
Edit: btw, the compiler error for eg #2 is "error: array type has incomplete element type" on the line of the cast.
I probably had done some 2d arrays (on the stack at least) and the concept that it's just one chunk of memory with a complex index is clear enough. I'm doing some stuff in c again needing to dynamically allocate a 2d array of integers so I assumed that you could use a double pointer just like a 2d array, but of course I'm wrong.
After reading a bit and thinking I get it that an int ** needs a series of seperately allocated chunks because the first array is an array of pointers. Am I correct in my understanding that you then access it with the same syntax as a 2d array on the stack and the compiler will figure out whether or not to use the indirection to follow your indices? (see code eg #1
Also, is it not possible to malloc a single block and use a cast to trick the compiler into accessing it like a stack 2d array? See code eg #2 for how I picture this (it's not working, obviously).
Edit: btw, the compiler error for eg #2 is "error: array type has incomplete element type" on the line of the cast.