Friday, 2 March 2018

c - Assign pointer to block reserved with malloc

Answer


Based on this answer: https://stackoverflow.com/a/19765782/1606345




#include 

typedef struct {
int *arr1;
int *arr2;
} myStruct;

myStruct *allocMyStruct(int num)
{
myStruct *p;


if ((p = malloc(sizeof *p +
10 * sizeof *p->arr1 +
10 * num * sizeof *p->arr2)) != NULL)
{
p->arr1 = (int *)(p + 1);
p->arr2 = p->arr1 + 10;
}
return p;
}


void initMyStruct(myStruct * a, int num)
{
int i;

for (i = 0; i < 10; i++) a->arr1[i] = 0;
for (i = 0; i < 10 * num; i++) a->arr2[i] = -1;
}

int main (void)

{
int num = 3;

myStruct *a = allocMyStruct(num);
initMyStruct(a, num);
free(a);
return 1;
}



It is safe to assign p->arr1 to the address of (p + 1)?



p->arr1 = (int *)(p + 1);

No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...