I want to know why structure variable passes pointer variable to create memory.
what happens if we do
box *boxes = malloc(n * sizeof(box));
Then we pass address to
scanf
function. Pointer actually stores the address. Then why we pass "&" of scanf to pointer ?
for (int i = 0; i < n; i ) {
scanf("%d%d%d", &boxes[i].length, &boxes[i].width, &boxes[i].height);
}
#include <stdio.h>
#include <stdlib.h>
#define MAX_HEIGHT 41
struct box
{
/**
* Define three fields of type int: length, width and height
*/
int length,width,height;
};
typedef struct box box;
int get_volume(box b) {
/**
* Return the volume of the box
*/
return b.length*b.width*b.height;
}
int is_lower_than_max_height(box b) {
/**
* Return 1 if the box's height is lower than MAX_HEIGHT and 0 otherwise
*/
return b.height < 41 ? 1 : 0;
}
int main()
{
int n;
scanf("%d", &n);
box *boxes = malloc(n * sizeof(box));
for (int i = 0; i < n; i ) {
scanf("%d%d%d", &boxes[i].length, &boxes[i].width, &boxes[i].height);
}
for (int i = 0; i < n; i ) {
if (is_lower_than_max_height(boxes[i])) {
printf("%d\n", get_volume(boxes[i]));
}
}
return 0;
}
- When I tried running the sizeof struct,I got the sizeof Struct box it was 12.
- Say n = 5, Then what will be the memory space? memory = 12 * 5 ?
CodePudding user response:
malloc()
is used to allocate dynamic and variable sized memory. So we use this to create an array ofn
structures.You need
&
becausescanf()
needs the address of the variable to store the input data to.b
is a pointer, butb[i].length
is just an ordinary structure member accessed by dereferencing that pointer. You need to get its address to pass toscanf()
.
CodePudding user response:
box *boxes = malloc(n * sizeof(box));
Allocates enough space for n instances of box on the heap and returns a pointer to it
scanf("%d%d%d", &boxes[i].length///
is passing the address of boxes[i].length
to scanf. Scanf needs to write there so its needs the address. Its just like
scanf("%d", &n);
that you did earlier
sizeof(struct box)
equaling 12 is fine. It has 3, 4 byte integers. You wont always get it that simply , the compiler might pad the structure to align things on 2, 4 or 8 byte boundaries, this is why sizeof
exists
Say n = 5, Then what will be the memory space? memory = 12 * 5 ?
yes