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

前端 未结 3 1624
后悔当初
后悔当初 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条回答
  •  难免孤独
    2021-01-17 03:07

    int *anint = 42;
    

    This declaration is incorrect. anint is a pointer to an int, but you've initialized it as an int.

    char *pointer_to_strlit;
    char *strlit = "some stuff";
    

    These declarations are fine. "some stuff" is a string literal, which in C is a char *, so it's fine to initialize strlit with it.

    pointer_to_strlit = &strlit;
    

    This is incorrect. &strlit is a char**, since it's the address of a char*.

    printf(
        "I print strlit: %s\n"
        "I print it again by pointing to it: %s\n"
        "I print where the pointer is pointing: %p\n", 
        strlit, *pointer_to_strlit, pointer_to_strlit
    );
    

    Here you use strlit as %s, which is fine. Then you use *pointer_to_strlit as %s, which is bad: %s expects a pointer to a null-terminated string, you gave it a char, so it segfaults.

提交回复
热议问题