In C, why can't an integer value be assigned to an int* the same way a string value can be assigned to a char*?

后端 未结 5 908
北荒
北荒 2020-11-29 09:01

I\'ve been looking through the site but haven\'t found an answer to this one yet.

It is easiest (for me at least) to explain this question with an example.

I

5条回答
  •  一个人的身影
    2020-11-29 09:21

    i'll split my answer to two parts:

    1st, why char* str = "hello"; is valid:

    char* str declare a space for a pointer (number that represents a memory address on the current architecture)

    when you write "hello" you actually fill the stack with 6 bytes of data
    (don't forget the null termination) lets say at address 0x1000 - 0x1005.

    str="hello" assigns the start address of that 5 bytes (0x1000) to the *str

    so what we have is :
    1. str, which takes 4 bytes in memory, holds the number 0x1000 (points to the first char only!)
    2. 6 bytes 'h' 'e' 'l' 'l' 'o' '\0'

    2st, why int* ptr = 0x105A4DD9; isn't valid:

    well, this is not entirely true!
    as said before, a Pointer is a number that represent an address,
    so why cant i assign that number ?

    it is not common because mostly you extract addresses of data and not enter the address manually.
    but you can if you need !!!...
    because it isn't something that is commonly done,
    the compiler want to make sure you do so in propose, and not by mistake and forces you to CAST your data as
    int* ptr = (int*)0x105A4DD9;
    (used mostly for Memory mapped hardware resources)

    Hope this clear things out.
    Cheers

提交回复
热议问题