Home > Blockchain >  Type casting from char* to int*
Type casting from char* to int*

Time:09-27

I am learning c in school , and having a little confusion on how to use type casting. here is my code.

I am trying to figure out what type casting is and how it works.

I initialized a pointer(ptr3) that points the adress of k, then initialized ptr4 and assign ptr3 that is converted into int*.

but this does not seem like working, since it gives random values every time.

Why is it?

I appreciate any feedback ! thank you so much.

#include <stdio.h>


int main() { 
 
  char k = 10;
  
  char* ptr3 = &k;

  int* ptr4 = (int*) ptr3; 
  
  printf("*ptr3  = %d *ptr4  = %d\n", *ptr3, *ptr4); 
  

  return 0;
}

output is

*ptr3  = 10 *ptr4  = 1669824522

CodePudding user response:

You have two undefined behaviour in one line.

  1. When you dereference int * pointer you read outside the k object which is illegal.
  2. Even if the k had enough size (for example is a char array), using the data as another type violates the strict aliasing rules - which is UB as well

Generally speaking, do not typecast pointers unless you really know what you are doing. If you want to convert byte array to integer use memcpy functionh.

CodePudding user response:

A char is 1 byte in size, however, an integer is 4 bytes.

What you are doing is called Type Punning, where you are telling the compiler to not convert your char to an int and directly read 4 bytes from that same memory address while you are only allocating 1 byte. Those other 3 bytes could be anything.

The bytes of the char look like this:

10

Real simple, only one number. Integers need 3 more bytes than a char so here is what the integer could look like in bytes:

10 ? ? ?

The solution:

#include <stdio.h>

int main() 
{ 
    char k = 10;
    int i = (int)k;

    printf("k = %d  i = %d\n", k, i); 

    return 0;
}

This code instead of directly reading the memory tells the compiler to convert the char to an int, filling in those 3 random bytes in the process with zeros. Here is what the variable i could look like in memory:

10 0 0 0

Those last 3 bytes were filled in with zeros and the integer is 10.

I hope this answer helps and I am open to feedback to improve it.

  • Related