Answer to simple C Question

Answer sign
Image by Gerd Altmann from Pixabay

Hopefully you got choice 2. 62. Here’s the question again.

#include <stdio.h>
int main() {
	float* p = (float*)50;
	p = p + 3;
	printf("%u\n", p);

The first line in main() creates a “pointer to a float” p with the initial value 50. This 50 is the value of p i.e. the address that p is pointing to, NOT the value at that address P is pointed to.

Adding 3 to p moves the pointer by 3 x the size of a float. As it’s unspecified, this size of a float is typically 32-bits or 4 bytes. So this line adds 12 to p. It now has the value 62.

You can try this out and step through it on the Python Tutor. Despite its name, it will let you run run programs in Python, C, C++, Java, JavaScript, TypeScript and Ruby. It compiles C with GCC 4.8 and uses a Valgrind Memcheck plugin. There are a few restrictions its quite a nice way to show off execution of simple programs.