0

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.

belkka
  • 264
  • 2
  • 13
  • 1
    there's no porttable way to initialize pointers with literal addresses except 0. Somtimes I've seen things like `T *ptr = (T *)1;` if you need another special value besides `NULL` but I doubt that this is covered by the standard. And doing pointer arithmetics when the pointer isn't poperly initialized always invokes Undefined Behaviour – Ingo Leonhardt Nov 24 '20 at 13:20
  • What is "properly initialized pointer" and how does it differ from "improperly initialized pointer"? Does "improperly initialized pointer" differ from "uninitialized pointer"? – belkka Nov 24 '20 at 13:34
  • how about this `int *p; p = (void* )5;` – csavvy Nov 24 '20 at 13:34
  • Duplicate: [“Pointer from integer/integer from pointer without a cast” issues](https://stackoverflow.com/questions/52186834/pointer-from-integer-integer-from-pointer-without-a-cast-issues). – Lundin Nov 24 '20 at 15:11
  • 1
    "Is "cast" word used as synonym for "explicit cast"" Casts are always explicit. A cast is an explicit _conversion_ done by the programmer. As opposed by implicit conversions that are done by the C language compiler. – Lundin Nov 24 '20 at 15:12
  • @Lundin thanks for explanation; I used to interpret "cast" and "conversion" as synonyms. Your explanation answers my question, because this means that warning unambiguously says about lack of *explicit conversion* – belkka Nov 24 '20 at 16:13

1 Answers1

1

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.

dbush
  • 205,898
  • 23
  • 218
  • 273