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);
Subscribe to:
Post Comments (Atom)
casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & 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...
-
The whole error output being: LNK2019 unresolved external symbol wWinMain referenced in function "int __cdecl __scrt_common_main_seh(vo...
-
I have come across CORS issues multiple times and can usually fix it but I want to really understand by seeing this from a MEAN stack paradi...
-
I recently used canvas to conert images to webp, using : const dataUrl = canvas.toDataURL('image/webp'); But this takes a lots of ti...
No comments:
Post a Comment