I have this:
unsigned int y = (unsigned int)(int*)foo;
How do I get the address to where is stored in memory value which foo points?
Let's try to explain better, assume that thery are of int type:
int x = 10;
int *foo = &x;
unsigned int y = (unsigned int)(int*)foo;
int r = MAGIC(y); /* should be 10 */
x = 13; /* r still should be 10 */
y should hold x's adddress, it is, address of 10 integer.
r should copy the value at y location, it is, 10 integer.
so any change of x (as in x = 13) shouldn't change value r. This just an int.
The question is: How do I define MAGIC?
If what you want is possible, then
#define MAGIC(y) (*((int*)(y)))
will do it.
Your code is trying to use y as a pointer when in fact it is defined to the C-compiler as an unsigned integer. Code that was written back in the "bad ol' days" would do stuff like your example.
Code should be more explicit and well defined in its intent, thus:
#include <stdlib.h>
main()
{
int x = 10;
int *foo = &x;
int *y = foo;
#define MAGIC(A) *A
int r = MAGIC(y); /* should be 10 */
x = 13; /* r still should be 10 */
printf("x=%d, r=%d", x, r);
// printed (as expected) :: x=13, r=10
}
These days there is NO reason to work around a C-compiler!!
If you are maintaining some old code that does stuff like your original example, then it is probably worth the effort to re-write it using today's programming style. Note, it can remain written in C, just well-formed C!
If y is to hold the address of x then it should be declared as:
unsigned int *y;
MAGIC should simply be the what is pointed to by operator.
int r = *y;
MAGIC is just the asterisk.
Related
The question surely look stupid, but I have always wasted a lot of time, with tests/errors until it works, with this kind of problem.
I need a pointer to return a value from a function, then I need to divide this value, but I have the compiler error:
invalid operands to binary / (have 'int *' and 'int')
Example in the following code:
void test(int *x, int y)
{
*x = *x+y;
}
int main()
{
int *x = 20;
int y = 1;
test(&x, y);
printf("x: %i", x);
float res = x / 2; // error: invalid operands to binary / (have 'int *' and 'int')
//float res = *x / 2; // application crash with this one. (GCC native Android)
}
I tried with '&' but it didn't work (x = 0), I try cast to int and only get the pointer adress, etc.
Your immediate problem is that you have declared x as a pointer to int, but you are trying to use it as an int. To simply correct the last line, dereference the pointer (just like you've correctly done inside test()):
float res = *x / 2;
Now, it appears you actually tried that and got an error, which is not surprising, because you've initialized x badly:
int *x = 20;
This doesn't create an int value of 20 and make x point to it. It sets x to point at the memory address represented by the integer value 20. That's probably reserved memory, which is why you get an error when you try to dereference it.
(You don't get that error in test() because you've passed the address of x as the argument. So dereferencing it there actually does get you 20 - probably.)
To make the pointers work, either do:
int x = 20;
...
test(&x, y)
...
float res = x / 2;
or:
int *x = malloc(sizeof(int));
*x = 20;
...
test(x, y)
..
float res = *x /2;
But you are really making this too difficult. Since you only need to output one value from the function, just make the function return that value. Then you have no need to mess about with pointers at all:
int test(x,y) { return x+y; }
...
int x = 20;
...
x = test(x,y);
...
float res = x / 2;
(And finally, I believe that in any case you want to use 2.0 in the last line, not just 2, if you want to get a float result instead of an int.)
int * x = 20; means: x is a pointer to an int stored at address 20. When you deference it, the CPU will try to read an int value from address 20, yet address 20 is an invalid address in your current process space and thus your program crashes.
What you probably wanted do say is: x is a pointer to an int and the value of the int it points to is 20, correct? Well, this would have been:
int someInt = 20;
int * x = &someInt;
Now x points to whatever address someInt stores its value (actually it's on the stack space of the main function, but that's just a side node) and the value stored at that address is in fact 20.
#include <stdio.h>
void main()
{
int s = (char)1;
int *p = &s;
printf("%x", *p);
}
output
1
I tried to find out if int type variable is declared and substitute for char type value 1, rest of 3 bytes of variable s is initialized or not. For this output, can I think each of 24 bits of variable s is initialized as 0?
What happen?
The smaller type gets implicitly cast back to the larger type, so your explicit type cast does nothing effectively (except that larger values may be truncated).
Functionally, these two lines are identical:
int x = (char) 1;
int y = (int)(char) 1;
And these two lines are identical as well:
int x = (char) 257; // Truncated to 1
int y = 1;
our teacher gave us the following code:
x = **(&d);
His question was: "Which lines of codes do you have to add above this line, so that the code is correct?"
Can anybody help me? What is the meaning of this line?
The remark of DeiDei is a possibility, I just explain more here
We are in C, and to simplify consider x and d are not macros.
x = **(&d); is equivalent to x = *d; because to get the address then dereference does nothing
Now the question is to find a context where x = *d; is legal, for that d has to be a pointer. Let say int * d;
Probably also the goal is to not have a segmentation fault so d need to memorize a valid address. Let say int a; int * d = &a;
Now we assign x with *d so the type of x must be compatible with int Let say int a; int * d = &a; x = **(&d);
To be clean we do not want to access to an uninitialized value, because x finally receive the value of a that one must be initialized.
int a = 0; int* d = &a; int x; x = **(&d); from DeiDei is compatible with the requirement, but of course they are plenty of other solutions
x = **(&d);
is equivalent to
x = **&d;
is equivalent to
x = *(*&d);
also for any variable v this
v == *&v
holds true.
From the above it concludes that
*&d == d
so
x = *(*&d);
equals
x = *d;
As the dereference operator * can only be applied to a pointer it follows the d has to be of a pointer type
T * d; /* Let be T any type. This defined d to be pointer to that type T. */
Applying to a variable of type T* the operator * the result evaluates to the type T itself.
As it is given
x = *d
from this it concludes that x needs to be of type T.
So the line in question needs to be
T x, *d;
or in a more readable form
T x;
T * d;
:-)
I'm trying to program an algorithm that uses the order of five separate integers to determine what to do. However I need to know in which order the integers come. I'm new on this site, so I'm sorry if this question is to vague or the info given is not enough. Here is the code:
{
#include <stdio.h>
int main ()
{
int a=1;
int b=0;
int c=0;
int d=1;
int e=1;
/* Program that determines the order. */
return 0
}
As you can see int a is created before int b. b before c ect. I need a program that can "call" (so to speak) the integer that came 1st, 2ed, ect. in sequence. How do I do that?
You must check adresses of int by using :
&a; &b...
then the order of int should appear by ascending order.
Care about adress of local var without pointers.
Adresses are only available on local function, if you pass them as arguments in other function, local variable will be duplicate so the adress will change !
Get adresses of your int (code):
int addr[5];
addr[0] = &a; // if &a == 0 {
addr[1] = &b; // &b = sizeof(int) * 1
addr[2] = &c; // &c = sizeof(int) * 2
addr[3] = &d; // &d = sizeof(int) * 3
addr[4] = &e; // &e = sizeof(int) * 4 }
I have an array of arbitrary values, so I have defined it as an array of void pointers, so I can point to any kind of information (like int, character arrays, etc). However, how do I actually assign an int to it?
Take for example these initializations:
void* data[10];
int x = 100;
My intuition would think this, but this gives a compile error:
data[0] = malloc(sizeof(int));
*(data[0]) = x;
Also I thought about using &x, but I would take the address of a local variable, which (to my understanding) would be cleared after exiting from the procedure. So if I have a local variable x, how would I get it into a void pointer type of variable correctly?
*((int*)data[0])=x;
will do it.
You might want to consider using a union. Something like this:
union myvalues
{
int i;
double d;
long l;
};
You could then have
union myvalues *foo[10];
foo[0] = malloc(sizeof(union myvalues));
foo[0]->i = x;
You can also typedef the union. sizeof(union myvalues) will be the maximum of sizeof the members. So if you have int i; and char c[40] in the union, sizeof(union myvalues) will be 40. Writing to i will then overwrite the first 4 characters in c (assuming your ints are 4 bytes).
*((int *)data[0]) = x;
A copy of x will be made, so the fact it is a local variable is not important.
for aliasing reasons its far better to do
mempcy( data[0], &x, sizeof( int ) );
As it happens the compiler will optimise the memcpy call out as sizeof( int ) is a constant value but it won't break various aliasing rules.
Although you can use a cast to make the assignment, it is probably much cleaner to write the code like:
void *data[ 10 ];
int x = 100;
int *p;
p = malloc( sizeof *p );
data[ 0 ] = p;
*p = x;
try this:
data[0] = malloc(sizeof(int));
*((int*)data[0]) = x;
or
(int) (*(data[0])) = x;
don't forget to
free (data[0]);
afterwards.