PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 4, 2022

[FIXED] How to cast and pass the address of a variable to a function in C

 July 04, 2022     address-operator, c, casting, function-call, pass-by-reference     No comments   

Issue

Let's imagine that I have a variable of type int which I would like to pass to a C function as a parameter. This function expects that the parameter is a pointer of type long long. Is it possible to cast this variable and then pass its address to the function like this and without using additional variables in the program:

int val;

val = 10;

my_function((long long) &val);



void my_function(long long *parameter)
{
     // do some operations with 'parameter'
}

Not sure if this code has hidden effects.


Solution

No. You must pass the correct pointer type.

long long is 8 bytes (probably), int is 4 bytes (probably) and if you try to pretend an int is a long long, when the code actually uses the pointer it will access the int plus another 4 bytes next to it, which will screw things up.

You must actually use a long long variable:

long long llval = val;
my_function(&llval);
val = llval; // if needed


Answered By - user253751
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing