Friday, March 2, 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

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...