- It won't compile
- It will compile, but it will segfault when we try to run it
- It will run and print 4 times 30
- Anything else you can think of
Highlight text bellow code to find out correct answer.
/* compile with cc -g -o test_typedef_sizeof test_typedef_sizeof.c */
#include <stdio.h>
#include <string.h>
typedef char name_t[30];
void fn(name_t value)
{
printf("%d\n", sizeof(name_t));
printf("%d\n", sizeof(value));
}
int main (void)
{
name_t aa;
printf("%d\n", sizeof(name_t));
printf("%d\n", sizeof(aa));
fn(aa);
return 0;
}
I'll just show you program output:
30
30
30
4
Is it not, what you have expected ? Fine, let's walk the program together. On entry to main() program prints sizeof(user defined type name_t), which has length of 30 chars. Next it'll print sizeof(instance of name_t) which again is 30 chars long. Then it calls function fn(instance of name_t), In fn() it prints sizeof(user defined type name_t) which is again 30 bytes. But when it tries to print sizeof(value) it prints 4, because arrays are passed as reference to first element in C/C++. And the sizeof(pointer) is 4 respectively 8 for 64 bit system.
No comments:
Post a Comment