I am preparing to take my c certification exam and one of the practice questions really has me stumped. I am hoping some c experts can help me understand this code (yes, I know this code is contrived, but that is what I am dealing with to pass this cert test):
#include <stdio.h>
#include <stdlib.h>
int main(void) {
float *t = 1 + (float *) malloc(sizeof(float) * sizeof(float));
t--;
*t = 8.0;
t[1] = *t / 4.0;
t++;
t[-1] = *t / 2.0;
printf("%f\n",*t);
free(--t);
return 0;
}
I am going to note down what I believe each line does and would verification/corrections.
1: Defines variable t which is a pointer to type float. Since I don't know how many types this system is running on, I don't know how to know what size of memory is being allocated. After the allocation, we add 1 which I think should move the pointer, but not sure
2: Moves the pointer back one?
3: Assigns the value 8.0 to the memory pointed to by t
4: Divides 8.0 (*t) by 4.0 and comes up with 2, but I don't understand what t[1]is in this case
5: Move the pointer? But to where since this is of type float *
6: Moves the pointer back 1 and assigns *t / 2.0 (couldn't figure out what *t is at this point)
7: prints out the value pointed to by t
8: frees the memory pointed to by --t