RE: [Dev-C++] dynamic allocation and structs
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Ioannis V. <no...@ho...> - 2002-10-24 20:57:27
|
> -----Original Message-----
> From: dev...@li...
> [mailto:dev...@li...] On Behalf
> Of Per Westermark
> Sent: Thursday, October 24, 2002 4:13 PM
> To: Scott Williams
> Cc: dev...@li...
> Subject: Re: [Dev-C++] dynamic allocation and structs
>
>
>
> // Alternative 1, array of entries.
> mystruct *myarray;
> void func(int count) {
> int i;
> myarray = (mystruct*)malloc(count*sizeof(mystruct));
> for (i = 0; i < count; i++) {
> myarray[i].xx = yy;
> }
> }
>
> // Alternative 2, array of pointers to entries.
> mystruct **myarray;
> void func(int count) {
> int i;
> myarray = (mystruct**)malloc(count*sizeof(*mystruct));
> for (i = 0; i < count; i++) {
> myarray[i] = (mystruct*)malloc(sizeof(mystruct));
> myarray[i]->xx = yy;
> }
> }
The Alternative 2 is wrong. You use a ** pointer and then you assign
values as if it is a *.
A working example of what you are trying to do:
#include <stdlib.h>
#include <stdio.h>
int main()
{
struct mystruct
{
int x;
};
struct mystruct **myarray;
int i, j;
/* sizeof(*myarray)==sizeof(struct mystruct *) */
myarray=malloc(100*sizeof(*myarray));
/* sizeof(**myarray)==sizeof(struct mystruct).
A 200x100 array on the free store is created */
for(i=0; i<100; i++)
myarray[i]=malloc(200*sizeof(**myarray));
/* Do something */
for(i=0; i<100; i++)
for(j=0; j<200; j++)
{
myarray[i][j].x=i+j;
printf("%d\n", myarray[i][j].x);
}
for(i=0; i<100; i++)
free(myarray[i]);
free(myarray);
return 0;
}
Alternative 3 (which must be prefered if possible instead of A-2):
#include <stdlib.h>
int main()
{
struct mystruct
{
int x;
};
struct mystruct (*myarray)[100];
/* sizeof(*myarray)==sizeof(struct mystruct).
A 200x100 array on the free store is created */
myarray=malloc(200*sizeof(*myarray));
/* Do something */
free(myarray);
return 0;
}
Ioannis
* Ioannis Vranos
* Programming pages: http://www.noicys.freeurl.com
* Alternative URL: http://run.to/noicys
|