0
votes

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]));

}

1
I think you are looking for a 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 - Chintan
You are storing the value of an unsigned short int* pointer value inside a char variable myMemory[i] = p. Please read compiler warnings. You are not storing unsigned short value inside char * 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. printf and the output you get and the output you expected to see? - KamilCuk
@KamilCuk code has been updated with the print statement I am using to see if the myMemory index is an integer or an unsigned short int. I believe my problem has something to do with casting, or not using pointers correctly. Sorry i forgot to include the actual printf statement result but it is this "testing size of an index 1" while it should be "testing size of an index 2" as I want the char array to hold an unsigned short int - user9543040
sizeof(myMemory[2]) is sizeof(*(char*) is sizeof(char) which is by definition always 1. index 2 - then print the index 2 not sizeof() from an element. char has 8 bits, unsigned short int probably has 16 bits, how do you want to store the short int inside char array? Big endian? Little endian? - KamilCuk
@KamilCuk Updated my previous comment, but I see what you are saying now. Is it possible that I need to make a print statement that points to the object the index is holding? I am sorry, I'm fairly new to C and the usage of stackoverflow. - user9543040

1 Answers

0
votes

I think you're looking for

char* myMemory = malloc(sizeof(*p) * 36);
for (int i=0; i<36; ++i) {
    memcpy(myMemory+i, p, sizeof(*p));
    i += sizeof(*p);
    ++p;
}

But you could simply use

char* myMemory = malloc(sizeof(*p) * 36);
memcpy(myMemory, p, sizeof(*p) * 36);
p += 36;

Note that incrementing a pointer causes it to move forward to the next element, so ++p advanced the pointer by sizeof(*p) bytes, and p += 36 advances it by sizeof(*p) * 36 bytes.