3

I have a question to the conversion of int array to char*. The following code has the output 23. But I don't really understand why. Can someone explain it to me?

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

int main(){
    uint32_t x;
    uint32_t* p = (uint32_t*) malloc(sizeof(uint32_t));    
    uint32_t array[9] = {42, 5, 23, 82, 127, 21, 324, 3, 8};

    *p = *((char*)array+8);
    printf("1: %d\n", *p);
    return 0;
}
1

3 Answers 3

6

The size of a uint32 is 32 bits, or 4 bytes. When you do (char*)array+8, you cast the array into an array of char, and take the eighth character. Here, the eighth character contains the beginning of the integer 23, which fits into a char.

Sign up to request clarification or add additional context in comments.

Comments

4
*p = *((char*)array+8*sizeof(uint32_t)

to move to array[8] in your example you are only moving 8 bytes forward

Comments

3

If you think about it, you have casted the array to char*. Where sizeof char is 1B. Which means usage pointer arithmetics in this case +8 doesnt move you 8*sizeof(uint32_t) to nineth element of array, but only 8 Bytes (8*sizeof(char)).

Since uint32_t has 4 Bytes, you have moved to first byte of 3rd element 23.

First you have to use pointer arithmetics on uint32_t array and after that cast it to char, like

*p = (char)*(array+8);  // Prints 8

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.