Why it is possible to assign string to character pointer in C but not an integer value to an integer pointer

后端 未结 3 1793
闹比i
闹比i 2021-01-19 14:56

why in the below code int *p = 22 will give compile time error and ptr will print the value successfully .

int main()
{

/*taking a character pointer and ass         


        
3条回答
  •  滥情空心
    2021-01-19 15:38

    This line assigns the memory address to be 22. This is incorrect. While this line will compile with only a warning, it will crash your program at runtime when you try to access memory address 22 later in the code.

    int *p = 22 ; //incorrect
    

    This will give you the result you're looking for:

    int *p = NULL;
    int val = 22;
    p = &val;
    

    Also

    printf("%d",p); //incorrect and give compile time error.
    printf("%d",*p); //you must derefence the pointer
    

    %s takes a pointer to char, where it is a null terminated string, while %d takes an int, not an int*.

提交回复
热议问题