SE250:lab-2:vpup001
This lab is focusing on pointers.
1) The first step is to determine the size of a pointer. This can be done by sizeof() operator. Create a code to print the size of the pointer and check if all the pointers have same size.
int main (void){ int x = 10; int *p; p = &x; printf("%d\n",sizeof(p)); return 0; }
The size of the pointer is printed as '4' when the program was run. The size always remained the same no matter what the data type is. The program was tested by changing the data types of the variable 'x' and pointer 'p' to double, int, char, and long. The pointer always have a size of 4 bytes.
I got different values for the size for the data types at first because I have changed the format string in the printf function each time I changed the data type. The format string is always "%d" as we are printing out the size not the value of the variable.
2) The second step is to see the difference between the addresses of two int variables x, y.
int main (void){ int x; int y; printf("&x = %p, &y = %p, diff = %ld\n", &x, &y, (long)(&x - &y)); return 0; }
The addresses of x and y are displayed when the program is run and the difference between them is 3.
Now the prinf is slightly changed.
printf("&x = %p, &y = %p, diff = %ld\n", &x, &y, (long)&x - (long)&y);
The addresses are different from earlier and the difference is now 12.
This difference is different each time because in the earlier case, we have calculated the difference of the address and then changed it to long but in the latter, the addresses are changed to long and then the difference is calculated.
BUT WHY ARE THE ADDRESSES DIFFERENT EACH TIME?
3) char is declared between x and y.
- The size of the array of 4 chars is displayed by using sizeof() operator.
- &arr prints out the address of first index of the array.
arr+4 prints out the address of first index +4 moved up.
&arr[4] prints out the address of 4+1 index (since the array has indexes 0,1,2,3)
arr+4 and &arr[4] have same values.
- For the array size 1,2,3,4 the difference between &x and &y is 6.
For the array size 5,6,7,8 the difference between &x and &y is 7.
For the array size 9 and 10 the difference between &x and &y is 8.
- when x and y are set to 0 and arr[4] is set to 10, the values are x and y are printed out as 0 as expected.
4) x and y are declared as global variables.
Obviously, the size of the array is still the same.
- The addresses of arr+4 and &arr[4] are same.
- For all the array size 1 to 10 the difference between &x and &y is 1.
- The values of x and y are printed out as 0 as were set to 0.
The difference between the addresses of x and y always remains the same when they are declared as global variables whereas it changes when they are declared as local variables.
5)The value of p1=2162356 and p2=2162344
WHY DO WE USE CURLY BRACES?