Answers/Solutions to Exercises in Chapter 9, Exercise 2

E2: Write access functions that can retrieve or store float value at any memory location without regards to memory alignment.

S2: A sample program is below. Notice that we really proved that it works regardless memory alignment: in main() we first store the float at address &buffer[11], and then repeated it at address &buffer[12]. It is not possible that both would be at the word boundary.

void store(float f,void* a)
{
	float v = f;
	char* from = (char*) &v;
	char* to = (char*) a;

	for(int i=0; i < sizeof(float); i++)
	  *to++=*from++;
}


float fetch(void* a)
{
	float v;
	char* from = (char*) a;
	char* to = (char*) &v;

	for(int i=0; i < sizeof(float); i++)
	  *to++=*from++;
	return v;
}

int main()
{
	char buffer[30];
	float f = (float) 2.35;

	store(f,(void*) &buffer[11]);
	printf("%f\n",fetch((void*) &buffer[11]));

	store(f,(void*) &buffer[12]);
	printf("%f\n",fetch((void*) &buffer[12]));
	return 0;
}

 

Back to Answers/Solutions Index                          Back to Answers/Solutions for Chapter 5 Index