In: Computer Science
Rewrite the C PROGRAMMING LANGUAGE CODE in terms of only dereferencing (*) and pointer addition (+) AND extend the code so that allocated memory is freed properly. Thank you
struct foo {
int a;
char b;
};
int main(void)
{
struct foo* arr[5];
int x;
for(x = 0; x < 5; x++)
{
arr[x] = malloc(sizeof(struct foo));
arr[x]->a = 0;
arr[x]->b = 'b';
}
}
Ans
Statement
struct foo* arr[5] creates array of pointers of size 5. Then allocate to each element.
Make 2d dynamic array
a[b] is equivalent to *(a+b)
.
.
code:-
struct foo {
int a;
char b;
};
int main(void)
{//dynamic 2D array of size 5xsize of struct
struct foo** arr =(struct foo**)malloc(5*sizeof(struct foo));
int x;
for(x = 0; x < 5; x++)
{//for each element of foo
//allocate struct
*(arr+x) =(struct foo*)malloc(sizeof(struct foo));
//set member a
(*(arr+x))->a = 0;
//set member b
(*(arr+x))->b = 'b';
}
screenshot with output
.
..
If any doubt ask in the comments.