How to explain C pointers (declaration vs. unary operators) to a beginner?

前端 未结 23 919
渐次进展
渐次进展 2020-11-30 18:08

I have had the recent pleasure to explain pointers to a C programming beginner and stumbled upon the following difficulty. It might not seem like an issue at all if you alre

23条回答
  •  难免孤独
    2020-11-30 18:11

    Basically Pointer is not a array indication. Beginner easily thinks that pointer looks like array. most of string examples using the

    "char *pstr" it's similar looks like

    "char str[80]"

    But, Important things , Pointer is treated as just integer in the lower level of compiler.

    Let's look examples::

    #include 
    #include 
    
    int main(int argc, char **argv, char **env)
    {
        char str[] = "This is Pointer examples!"; // if we assume str[] is located in 0x80001000 address
    
        char *pstr0 = str;   // or this will be using with
        // or
        char *pstr1 = &str[0];
    
        unsigned int straddr = (unsigned int)pstr0;
    
        printf("Pointer examples: pstr0 = %08x\n", pstr0);
        printf("Pointer examples: &str[0] = %08x\n", &str[0]);
        printf("Pointer examples: str = %08x\n", str);
        printf("Pointer examples: straddr = %08x\n", straddr);
        printf("Pointer examples: str[0] = %c\n", str[0]);
    
        return 0;
    }
    

    Results will like this 0x2a6b7ed0 is address of str[]

    ~/work/test_c_code$ ./testptr
    Pointer examples: pstr0 = 2a6b7ed0
    Pointer examples: &str[0] = 2a6b7ed0
    Pointer examples: str = 2a6b7ed0
    Pointer examples: straddr = 2a6b7ed0
    Pointer examples: str[0] = T
    

    So, Basically, Keep in mind Pointer is some kind of Integer. presenting the Address.

提交回复
热议问题