Pointer to an array and Array of pointers

前端 未结 6 2065
感动是毒
感动是毒 2020-12-22 00:47

As I am just a learner, I am confused about the above question. How is a pointer to an array different from array of pointers? Please explain it to me, as I will have to exp

6条回答
  •  清歌不尽
    2020-12-22 01:37

    I often resort to pen and paper when thinking about c pointers.

    Pointer to an array

    [a] -> [b]
           [c]
           [d]
            .
            .
            .
    

    An array of pointers

    [a] -> [j]
    [b] -> [k]
    [c] -> [l]
     .      .
     .      .
     .      .
    

    A pointer to an array contains the memory location of an array. Whereas an array of pointers contains lots of memory locations, which contain single values (or possibly other arrays, or arrays of pointers ;).

    Pointer to an array

    #include 
    #include 
    
    void main(void) {
        int i;
        int *ptr, *loopPtr;
        ptr = malloc(10 * sizeof(int)); // allocate an array of 10 ints on the heap
    
        loopPtr = ptr;            // copy pointer into temp pointer 
        for(i=0; i < 10; i++) {
            *loopPtr = i;         // dereference pointer and store i in it
            loopPtr++;            // move pointer to next memory location
        }
    
        loopPtr = ptr;            // copy pointer into temp pointer
        for(i=0; i < 10; i++) 
            printf("%d, ",*(loopPtr++)); // move across array printing
        printf("\n");
        free(ptr);               // free memory allocated on the heap
    }
    

    An array of pointers

    #include 
    #include 
    
    void main(void) {
        int i;
        int *ptr[10];            // an array of pointers
    
        // allocate 10 ints on the heap pointed to by an array
        for(i=0; i < 10; i++)
            ptr[i] = malloc(sizeof(int));
    
        for(i=0; i < 10; i++)
            *ptr[i] = i;         // dereference pointer and store i in it
    
        for(i=0; i < 10; i++)    // iterate through array and dereference pointers
            printf("%d, ",*ptr[i]);
        printf("\n");
    
        for(i=0; i < 10; i++)
            free(ptr[i]);
    }
    

    The best way to contrast the difference is probably with the malloc() calls, one returns a pointer to an array of 10 ints and the other returns 10 pointers to individual ints.

提交回复
热议问题