Answers/Solutions to Exercises in Chapter 9, Exercise 3
E3: Write a program that compacts a structure that has an int array, a float, a double, and a char, relativizes the segment where the structure iscompacted. Write access functions that can access (store or retrieve) the relativized compacted form of the structure.
S3: A sample solution program is below.
struct MYSTRUCT_STRUCT {
int array[7];
float f;
char c;
double d;
};
typedef struct MYSTRUCT_STRUCT MYSTRUCT;
float get_float(void* a)
{
float v;
char* to = (char*) &v;
char* from = (char*) a;
for(int i=0; i<sizeof(float); i++)
*to++=*from++;
return v;
}
void set_float(float f,void* a)
{
float v=f;
char* to = (char*) a;
char* from = (char*) &v;
for(int i=0; i<sizeof(float); i++)
*to++=*from++;
}
double get_double(void* a)
{
double v;
char* to = (char*) &v;
char* from = (char*) a;
for(int i=0; i<sizeof(double); i++)
*to++=*from++;
return v;
}
void set_double(double f,void* a)
{
double v=f;
char* to = (char*) a;
char* from = (char*) &v;
for(int i=0; i<sizeof(double); i++)
*to++=*from++;
}
int get_int(void* a)
{
int v;
char* to = (char*) &v;
char* from = (char*) a;
for(int i=0; i<sizeof(int); i++)
*to++=*from++;
return v;
}
void set_int(int f,void* a)
{
int v=f;
char* to = (char*) a;
char* from = (char*) &v;
for(int i=0; i<sizeof(int); i++)
*to++=*from++;
}
int GetArray(int i,void* segment)
{
char* p=(char*) segment;
p += i*sizeof(int);
return get_int(p);
}
void SetArray(int value,int i,void* segment)
{
char* p=(char*) segment;
p += i*sizeof(int);
set_int(value,p);
}
float Get_f(void* segment)
{
char* p=(char*) segment;
p += (7*sizeof(int));
return get_float(p);
}
void Set_f(float value,void* segment)
{
char* p=(char*) segment;
p += (7*sizeof(int));
set_float(value,p);
}
char Get_c(void* segment)
{
char* p=(char*) segment;
p += (7*sizeof(int)+sizeof(float));
return *p;
}
void Set_c(char value,void* segment)
{
char* p=(char*) segment;
p += (7*sizeof(int)+sizeof(float));
*p=value;
}
double Get_d(void* segment)
{
char* p=(char*) segment;
p += (7*sizeof(int)+sizeof(float)+1);
return get_double(p);
}
void Set_d(double value,void* segment)
{
char* p=(char*) segment;
p += (7*sizeof(int)+sizeof(float)+1);
set_double(value,p);
}
int main()
{
MYSTRUCT my;
for(int i=0; i<7; i++)
my.array[i]=10*i;
my.f=(float) 2.35;
my.c='A';
my.d= 3.21;
void* segment = (void*) malloc(7*sizeof(int)+sizeof(float)+1+sizeof(double));
for(i=0; i<7; i++)
SetArray(my.array[i],i,segment);
Set_f(my.f,segment);
Set_c(my.c,segment);
Set_d(my.d,segment);
for(i=0; i<7; i++)
printf("array[%d]=%d\n",i,GetArray(i,segment));
printf("f=%f\n",Get_f(segment));
printf("c=%c\n",Get_c(segment));
printf("d=%f\n",Get_d(segment));
return 0;
}
Back to Answers/Solutions Index Back to Answers/Solutions for Chapter 9 Index