When doing a code review I found that the programmer had accidentally passed a typedef object directly foo(foo)
when the function took a pointer as an argument foo(&foo)
. For some reason it still works as long as the typedef is an array and not e.g. a struct. Can someone explain why? See the following code:
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef uint8_t foo_t[3];
typedef uint8_t bar_t[2];
typedef struct __attribute__((packed))
{
foo_t foo;
bar_t bar;
} foobar_t;
void change_foo(foo_t foo)
{
foo_t bar = {1,2,3};
memcpy(foo, bar, sizeof(foo_t));
}
void change_foo_p(foo_t *foo)
{
foo_t bar = {1,2,3};
memcpy(foo, bar, sizeof(foo_t));
}
void change_foobar(foobar_t foobar)
{
foo_t bar = {1,2,3};
memcpy(foobar.foo, bar, sizeof(foo_t));
}
void change_foobar_p(foobar_t *foobar)
{
foo_t bar = {1,2,3};
memcpy(foobar->foo, bar, sizeof(foo_t));
}
int main()
{
printf("Hello, World!\n");
foobar_t foobar;
foobar_t foobar2;
foo_t foo;
foo_t foo2;
change_foo(foo);
change_foo_p(&foo2);
change_foobar(foobar);
change_foobar_p(&foobar2);
// Prints 1101 since the only method not working is change_foobar()
printf("%d%d%d%d\n", foo[0], foo2[0], foobar.foo[0], foobar2.foo[0]);
return 0;
}