Looking the following approach of initializing a structure, you can see that malloc was not used to allocate a size for params
in the main, it just pointed to to array
right away. It prints the values correctly but is this valid practice/ what difference does it make if I allocate a size before the assignment?
typedef struct _param_t {
char * params;
} param_t;
int main()
{
int i;
param_t r;
unsigned char array[5] = {0x01 , 0x02 ,0x03 ,0x04 ,0xFF};
r.params = (char *) array;
for (i = 0; i < 5; i++) {
printf(" Array %d is %x", i, r.params[i]);
}
return 0;
}
Output:
Array 0 is 1 Array 1 is 2 Array 2 is 3 Array 3 is 4 Array 4 is ffffffff
On another note, this is the prototype of fwrite used to write to a file:
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
It takes in a void pointer. In the main, I cast the array to a (char *)
to populate the structure. I know that converting between signed T* and unsigned T* in either direction is generally possible.
My questions is, what is the difference between writing r.params
to a file in binary mode with sizeof(unsigned char)
as size
VS sizeof(char)
as the size
parameter ? Both are the same size. Therefore is shouldn't make a difference and reading from the file can then be stored in a char array or an unsigned char array without loss of data, correct?