Reputation: 273
Here is a C program:
#include<stdio.h>
#include<stdint.h>
int main() {
int32_t *ptr = 5;
printf("ptr is %p\n", ptr);
printf("++ptr is %p\n", ++ptr);
}
The intention is to initialize a pointer with literal address (e. g. 5
) and look how it changes after increment.
gcc
produces following warning
warning: initialization of 'int32_t *' {aka 'int *'} from 'int' makes pointer from integer without a cast [-Wint-conversion]
6 | int32_t *ptr = 5;
| ^
What is the general way to avoid this warning?
Is "cast" word used as synonym for "explicit cast", so the intended fix is as following?
int32_t *ptr = (int32_t *)5;
Or maybe is there a special syntax for pointer literals?
For the purpose of the program it's possible to declare an additional variable to initialize pointer with its address (like int32_t x, *ptr = &x
) or even leave pointer uninitialized, but the question is about this specific warning and initializing pointers with literal values.
Upvotes: 0
Views: 2319
Reputation: 224437
You can silence the warning with an explicit cast as you've shown:
int32_t *ptr = (int32_t *)5;
However, the address 5 is most likely not one your process is allowed to write to and would invoke undefined behavior and would most likely crash.
Upvotes: 1