SE250:lab-2:tlou006

From Marks Wiki
Jump to navigation Jump to search

1

Using the code

printf("%d\n", sizeof(ip))

on the pointer variable ip returned a value of 4 on both the linux and PC.

Pointers are 4 bytes in memory.



2

printf("&x = %p, &y = %p, diff = %ld\n", &x, &y, (long)(&x - &y));

returned a difference of 4 on PC and 1 on linux.

I am not sure what this result means. Why would the pointers take up less space on linux?

The difference between (long)&x - (long)&y and (long)(&x - &y) is that the latter converts the answer from the

subtraction to type long while the former does the conversion to long before the subtraction.



3

Declaring an array of type char and size 4 between the integer declarations x and y

int x;
char arr[ 4 ];
int y;

Sizeof(arr) showed 4 as output. This was expected.

The address of &arr was 4 bytes in front of the address of &arr[ 4 ].

This means that &arr points to the first value in the array, something I should have known.



My initial thoughts were that the difference between the addresses of x and y would be bigger, due to the new

array taking up room in the memory. But



5

using the code

int *p1, *p2;
int q;
p1 = &q;
int r;
p2 = &r;

Gave outputs for p1/p2 as huge values on the PC. On linux it gave huge negative numbers as outputs.




7

After initialising a structure containing one of every variable type and running

printf("&my_struct = %p\n", my_struct);
printf("offsets:\n"
"my_char: %ld\n"
"my_short: %ld\n"
"my_int: %ld\n"
"my_long: %ld\n"
"my_float: %ld\n"
"my_double: %ld\n",
		
(long)&my_struct - (long)&my_struct.my_char,
(long)&my_struct - (long)&my_struct.my_short,
(long)&my_struct - (long)&my_struct.my_int,
(long)&my_struct - (long)&my_struct.my_long,
(long)&my_struct - (long)&my_struct.my_float,
(long)&my_struct - (long)&my_struct.my_double);

The output was

char 0 - meaning the char variable is first in the memory.
short -2 - followed by variable type short. Type char takes up 2 bytes.
int -4 - Short also takes up 2 bytes.
long -8 - Int takes up 4 bytes.
float -12 - Long takes up 4 bytes.
double -16 - I was told that a structure had size 24. Double takes up 8 bytes.



8

Using a union the output was

char 0 
short 0 
int 0 
long 0
float 0
double 0

I was a bit confused by this. Perhaps it means all the variable types are placed together in memory?

Need to know more about unions