Pointers and assignment, how does it work with different types?

前端 未结 3 1599
后悔当初
后悔当初 2021-01-17 02:09

I\'m doing \"Learn C the hard way\" for self-study coming from knowing a bit of Python. I have read several tutorials, but I can\'t get my head around how pointers and assig

3条回答
  •  -上瘾入骨i
    2021-01-17 02:50

    int *anint = 42;
    

    42 is an integer literal and anint is supposed to hold the address pointing to an integer and not by integer itself.

    char *pointer_to_strlit;
    char *strlit = "some stuff";    // Should be const char *strlit = "some stuff";
    pointer_to_strlit = &strlit;    // Wrong
    

    &strlit gives address of pointer ( i.e., char ** ) while pointer_to_strlit is of type char*. So, it should be

    pointer_to_strlit = strlit;
    

    String literals reside in read only location. Turn on the warnings and compiler should give you some decent messages.

提交回复
热议问题