Here is my following code, in my for loop I'm trying to store an unsigned short int inside of the char* memory created by malloc. I'm indexing to do this and I would like to keep it that way if possible.
However, inside myMemory when printing out a sizeof(myMemory[0]) or even printing out the address myMemory[0] itself, it seems that the integer value of p is being stored, not the unsigned short int. The integer itself is correct, but the byte size is 1, not 2, hence not an unsigned short int.
char* myMemory;
typedef unsigned short int R;
void main(){
R *p:
myMemory = malloc(65536)
for (int i = 0; i<36;i++){
myMemory[i] = p;
i++;
myMemory[i] = p;
p++;
p++;
}
printf("testing size of an index %d\n",sizeof(myMemory[2]));
}
union { char value[sizeof(unsigned short int)], unsigned short int p; }Then you can store an unsigned short int into p and read its bytes via char* values - Chintanunsigned short int*pointer value inside acharvariablemyMemory[i] = p. Please read compiler warnings. You are not storingunsigned shortvalue insidechar *variable.The integer itself is correct, but the byte size is 1, not 2, hence not an unsigned short int.- how do you check that? Can you post reproducible example with ex.printfand the output you get and the output you expected to see? - KamilCuksizeof(myMemory[2])issizeof(*(char*)issizeof(char)which is by definition always1.index 2- then print the index2notsizeof()from an element.charhas 8 bits,unsigned short intprobably has 16 bits, how do you want to store theshort intinsidechararray? Big endian? Little endian? - KamilCuk