Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

pointer to pointer to an 2D array of structs

TEST **CreateStruct2D(size_t i, size_t j)
{
TEST **end,**pi,**p;
int a =i*sizeof(TEST *);
p=(TEST**)malloc(i*sizeof(TEST *));
j*=sizeof(TEST);
for (end= p+i,pi=p;pi<end;++pi)
*pi=(TEST**)malloc(j);
return(p);
}

I have declared a struct TEST and am calling this routine from main using

pps = createrstruct2d(1,2)
[383 byte] By [hars113] at [2007-11-11 10:31:40]
# 1 Re: pointer to pointer to an 2D array of structs
what's the question exactly?
Danny at 2007-11-11 20:58:32 >
# 2 Re: pointer to pointer to an 2D array of structs
when i try to intialize this this array of structs it returns a error am not sure if i am coding it rite to create 2d array of structs and return the pointer to main program
hars113 at 2007-11-11 20:59:38 >
# 3 Re: pointer to pointer to an 2D array of structs
Best to use calloc() for allocating an array. Then, return the address of the allocated array.
This expression : p=(TEST**)malloc(i*sizeof(TEST *));
is wrong. i==sizeof TEST*, in other words, it's the size of a pointer. sizeof(TEST*) is also the size of a pointer. Furthermore, malloc isn't suitable for allocating arrays of objects/structs. It's better to use calloc, as said before.
Last, to avoid the complications of pointers to pointers, use a flat array: instead of arr[x][y], use arr[x*y] and then use a pointer to a pointer to iterate the one dimensional array.
Danny at 2007-11-11 21:00:42 >