• Log in or sign up for an account here: https://www.sythe.org/login

Structs are just abstractions (proof)

Govind

The One Musketeer
Joined
Apr 22, 2005
Sythe Gold
23
Messages
7,825
Structs are just abstractions (proof)
Proof that structs are just abstractions of contiguous memory:
Code:
#include <stdlib.h>
#include <stdio.h>
typedef struct __s1
{
	int a;
	int b;
} s1;

int main()
{
	long f = 0;
	s1 st;
	st.a = 7;
	st.b = 4;
	memcpy(&f, &st, 4);
	printf("%d\n", f);
	return 0;
}

f = 7.
 
Structs are just abstractions (proof)
Careful, the padding in a struct is based on the architecture's data alignment.
 
Structs are just abstractions (proof)
Would there be padding before the first variable? Besides, no type other than int is used.
 
Structs are just abstractions (proof)
Yikes SMR, I wouldn't do that except for experimental/demonstration purposes: as was correctly noted above, there is usually no padding before the first variable in a struct, but what if you were on an architecture where an int is 2 bytes, not 4? The result would be (7 << 2 | 4), whatever that works out to.
 
Runescape Gamblingrunescape gambling
Back
Top