Francogrex <> writes:
> I'm confused about 2 dimensional arrays and there memory storage and
> how to handle them using pointers; for example below something is
> wrong but can't spot why?
>
> #include <stdio.h>
> #include <stdlib.h>
>
> double **test ()
> {
> double **arr =malloc(100);
> arr[0][0] = 5.6;
> arr[0][1]=17.4;
> return arr;
Arrays are not pointers and pointers are not arrays. Your malloc line
allocates 100 bytes (that's odd in itself, but you're the boss) and
points to it with a pointer that will interpret those 100 bytes as a
sequence of pointers to doubles. Until you set those pointers to point
to something valid, you can't use arr[0][0] at all.
Your best bet is to start with the FAQ. It has a summary of how 2D
arrays can be allocated and used in C:
http://c-faq.com/aryptr/dynmuldimary.html
The FAQ is a little old, and if you have access to a compiler that
supports what are called variably modified arrays, you can often write
much neater 2D manipulation functions.
> }
>
> int main ()
> {
> double **myarray;
> myarray=test();
> printf("%f -- %f", myarray[0][0],myarray[1][1]);
> }
>
> // result: 5.600000 -- 17.400000 but expected to give error of
> myarray[1][1] not 17.400000
--
Ben.