i have a question about casting for pointers!

int *pointer = 30000; store address 30000 into pointer
int *pointer2 = pointer; // store address 30000 into pointer2

the above 2 statements are equivalent to....

int *pointer = (int*)30000;

is this statement correct? if not whats the difference! thx

I don't know why people have such difficulties with pointers. A pointer is a variable, its just like an integer variable except the values are memory addresses and the language C allows dereferencing pointers to obtain the value that's pointed to. Simple right?

Now your question. If you perform these operations

int *pointer = 30000; store address 30000 into pointer
int *pointer2 = pointer; // store address 30000 into pointer2

then pointer and pointer2 are storing the same values.

You could ask if

int x = 3000;
int y = x;

is x equivalent to y? Yes x and y values are equivalent.

There are really two answers to this question: 1) yes and 2) no.

Yes, because the cast in this case does no more than make an implicit conversion explicit. It is the same if you do float x = 12; -- you don't need to write float x = (float)12; because the conversion is done implicitly anyway (per C99 6.5.16.1p2 and 6.3.1.8). The cast is ugly and unnecessary.

No, because the statement p = 30000; (with or without a cast) invokes implementation-defined behavior. C99 6.3.2.3p5 states:

An integer may be converted to any pointer type. Except as previously specified [the previous clauses refer to the constant 0, which does have well-defined behavior when converted to a pointer], the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.

Pointers don't have to be integers; at least a few machines implement addresses as a segment+offset pair, and it's possible that more exotic implementations exist. Even on an implementation where pointers are integers, location 30000 might still not exist or point to something you can't modify (or that isn't even a memory location at all), causing your program to fail and potentially bringing your entire system down with it. Unless you know exactly 100% without a doubt what you are doing, don't mess around with that kind of thing.

(There is one exception to this rule. C99 introduces the intptr_t and uintptr_t types, which have the property that you can safely convert any pointer to void into one of these and back without loss of information. These types, while described in the Standard, are optional, so may not be available on all systems.)

commented: agree +35
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.