Search code examples
arrayscpointersimplicit-conversionpointer-arithmetic

How to Justify the Output of a Pointer To Pointer char array Program


#include <stdio.h>
#define STOP 0
void function(char**);
int main() {
    char*arr[] = { "icsp","hw6","fall","spring","autumn","winter" };
    function(arr);
    return 0;
}
void function(char**ptr) {
    char*ptr1;
    ptr1 = (ptr += sizeof(int))[-2];
    printf("%s\n", ptr1);
}

I have this code as my homework to explain how it works.I do not know how this pointer to pointer array really works and what does this line do ptr1 = (ptr += sizeof(int))[-2];? The output is

fall

I'll be so thankful if you explain it.


Solution

  • Within the function function the pointer ptr points to the first element of the array arr due to the implicit conversion of the last used as an argument of the function call

    function(arr);
    

    In this expression

    ptr += sizeof(int)
    

    there is used the pointer arithmetic. If to assume that sizeof( int ) is equal to 4 then the above expression is equivalent to

    ptr += 4
    

    That is now the pointer ptr points to the fifth element of the array arr, that contains a pointer to the string literal "autumn".

    Then there is used the subscript operator

    ptr1 = (ptr += sizeof(int))[-2];
    

    The expression

    (ptr += sizeof(int))[-2]
    

    is equivalent to

    *( (ptr += sizeof(int)) -2 )
    

    That is the pointer expression

    (ptr += sizeof(int)) -2
    

    points now to the third element of the array that is to the element (string literal) that points to "fall" (the pointer moved two positions left)

    Dereferencing the pointer

    ptr1 = *( (ptr += sizeof(int)) -2 )
    

    you get a pointer to the first character of the string literal that is outputted in this call

    printf("%s\n", ptr1);