Thread: Bit confused with this logic

  1. #1
    Registered User
    Join Date
    Apr 2019
    Posts
    35

    Bit confused with this logic

    I have seen several places like this
    Code:
    int main(int argc, char *argv)
    {
      char value=12;
      int *ptr = (int *)(&value); 
    }
    
    Complicated statements like structure in place of int means what? Why do you typecast?
    please help me to understand the use of the above statement. Will * and & not cancel out? Another statement like
    Code:
    int *ptr = (int *)(&value) and int *ptr = (int *) &value; both are same.
    Please help.

  2. #2
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    (int *) is a cast - It's more so for the intentional convention from char* to int*

    & is "address of"

  3. #3
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    https://www.tutorialspoint.com/cprogramming/c_type_casting.htm
    Last edited by Click_here; 05-27-2019 at 05:31 PM.

  4. #4
    Registered User
    Join Date
    May 2019
    Posts
    214
    I see you're asking this KIND of question in multiple places, so read my answer on your other recent question. What I'll say of the first example you post here is that it is likely going to crash because there's a fundamental error, which I can get to in the other answer (I'll be posting it shortly).

  5. #5
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    In the statement:
    Code:
    int *ptr = (int *)&value;
    You are getting the "address of" the variable "value" and initializing the pointer ptr with it. The (int *) is a casting (a conversion of types), so the compiler will not complain...

    But, beware: You are assigning the adress of an 8 bit type to a pointer which will access 32 bits (pointer to int). If you do:
    Code:
    *ptr = 0;
    In this case, the * is the OPERATOR of indirection (will take the address stored in ptr and access the data stored there), but will deal with 4 bytes, instead of a single one. It can cause segmentation fault or corrupt the contents of another variable or the stack.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. please help me with logic
    By Satya in forum C Programming
    Replies: 1
    Last Post: 05-21-2015, 12:47 PM
  2. confused on how the logic for this program
    By confused in c in forum C Programming
    Replies: 8
    Last Post: 11-04-2010, 05:25 PM
  3. Logic help...
    By csharp100 in forum C Programming
    Replies: 8
    Last Post: 09-14-2010, 11:29 PM
  4. Confused with specific && and || logic
    By the dead tree in forum Windows Programming
    Replies: 2
    Last Post: 04-23-2004, 01:03 PM
  5. Logic?
    By planet_abhi in forum Game Programming
    Replies: 1
    Last Post: 01-18-2003, 03:46 PM

Tags for this Thread