-
ahhh...that dp++
PHP Code:
typedef struct
{
char s1[90];
int I,j,k;
}
data_t;
data_t data, *dp;
strcpy(data.s1, "hi there");
data.i=1;
data.j=2;
data.k=3;
dp=malloc(sizeof(data_t)*100);
strcpy(dp->s1, "bye know");
dp->I=7;
dp->j=8;
dp->k=9;
dp++; //[COLOR=red]See below[/COLOR]
memcpy(dp, &data, sizeof(data_t));
Does "dp++;" create another pointer to data_t structure, so then you have another empty pointer to data_t?
-
No, it increments the pointer by either the sizeof(dp), or by 1(dont remember). This will probably make the pointer invalid, so dont do it =).
Z.
-
Thanks. A while back I was writing a class to total the amount of memory allocated during the program's execution, but couldnt call the constructor. I eventually just overloaded "new" to call my class's functions, and it works fine.
Z.
-
oh.
I use atexit(release) - then maintain a vector of pointers to each mem block malloc made and free() them in release().
Same idea.
-
I think something is wrong with his malloc(), should be,
dp=(data_t * )malloc(sizeof(data_t)*100);
before dp++; will work.
Or else how C will know how much to increment. By 1 int? by 1 char or by one data_t unit?
-
trans: it is valid C code (but not C++ since C++ wants explicit type casts when casting void pointers (void*) to other pointers). The compiler knows how much to increment because dp is:
data_t *dp;
C wouldn't care if he used
dp = malloc(11200);
(112 is the size of the structure and he wants 100 of them).
Actually, since sizeof is resolved by the compiler, it is exactly the same, except that if he one day decides to add a member to the struct, he'd have recalculate everything.
-
It increments the pointer by the size of what it is pointing to.
take a looksie...
long * pLong = malloc ( sizeof ( long ) * 100 );
char * pChar = (char *) pLong;
pLong++; // will increment the pointer by sizeof ( long )
pChar++; // will increment the pointer by sizeof ( char )
With VC++ you can not do this with a pointer to void. Not sure if this is a common thing or if its just the compiler I am using. Gives an error.
CornedBee: I'm not sure if this is what you just said or not... but I thought I would throw in my two-cents worth.
-
yeah, it is, but I don't care