I have a really irritating problem. This is the buffer structure i am using
typedef struct BufferDescriptor {
char * ca_head ; /* pointer to the beginning of character array (character buffer) */
int capacity ; /* current dynamic memory size (in bytes) allocated to character buffer */
char inc_factor; /* character array increment factor */
int addc_offset ; /* the offset (in char elements) to the app-character location */
int mark_offset ; /* the offset (in chars elements) to the mark location */
char r_flag; /* reallocation flag */
char mode; /* operational mode indicator*/
} Buffer ;
I cannot make any changes to above code. The inc_factor is supposed to be able to take values from 0 to 255.
therefore in the function where a buffer is created, i do the following so as to ensure that the inc_factor is not negative:
Buffer* b_create(int init_capacity, char inc_factor,char o_mode){
Buffer* buffer = (Buffer*)malloc(sizeof(Buffer));
buffer->ca_head=(char*)malloc(sizeof(char)*init_capacity);
buffer->inc_factor=(unsigned char)(inc_factor);
But the following line gives out a negative number:
printf("inc factor = %d",buffer->inc_factor);
What am I doing wrong here ? Plz Help.
You are formatting a
signedvariable as asignedvalue, so of course it will output a negative value if the variable exceeds 127. That is what happens when you store anunsignedvalue into asignedvariable – it wraps around to the negative. If you cannot change the variable type itself, then you have to change how it is being formatted (type-casting asignedvalue to anunsignedtype and then assigning to asignedvariable is pointless):Or: