In: Computer Science
Create a program that uses typedef to declare a new type vec2df which is a fixed double array of size 2. Next, create another type using typedef to declare a struct which has a fixed double array of size 2. Name this type vec2d. In main, declare two variables which use the types created above. Using stdlib.h, print the size of each variable on a new line and observe the similarity or difference. Finally, create two functions which take as input the types declared above as a single argument. For example, the first function takes vec2df as an argument and the second takes vec2d. In each function, print the size of the argument. Observe the difference in size between each instance. Save your code as prob5.c.
#include <stdio.h>
#include <stdlib.h>
typedef double vec2df[2];
typedef struct{double x[2];} vec2d;
void fun1(vec2df v1){
printf("sizeof of v1: %lu\n", (int) sizeof(v1)/ sizeof(v1[0])); // 8/8 = 2
}
void fun2(vec2d v2){
printf("sizeof of v2: %lu\n", (int) sizeof(v2)/ sizeof(v2.x[0])); // 16/8 = 2
}
int main() {
vec2df v1;
vec2d v2;
printf("Size Inside main\n");
printf("sizeof of v1: %lu\n", (int) sizeof(v1)/ sizeof(v1[0])); // 16/8 = 2
printf("sizeof of v2: %lu\n", (int) sizeof(v2)/ sizeof(v2.x[0])); // 16/8 = 2
printf("\nSize when passed as argument to external function \n");
fun1(v1);//8
fun2(v2);//16
return 0;
}
/*NOTE :
* We can use both the method to declare array using typedef
* typedef double vec2df[2];
* :However, this is probably a very bad idea, because the resulting type is an array type,
* but users of it won't see that it's an array type. If used as a function argument,
* it will be passed by reference, not by value, and the sizeof for it will then be wrong
*
* typedef struct{double x[2];} vec2d;
* : This is a better solution as it use pass by value.
*
* That's the reason why we see different size of the same type when used within the the scope of its declaration
* as compared to when we pass it as an argument.
*/