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

Time:12-11

#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.

CodePudding user response:

arr is array of char pointers.

arr
----
|  |->"icsp"
----
|  |->"hw6"
----
|  |->"fall"
----
|  |->"spring"
----
|  |->"autumn"
----
|  |->"winter"
----

When the function() function is called with passing arr argument, the function parameter ptr will point to array arr.

ptr- 
    |
   ----
   |  |->"icsp"
   ----
   |  |->"hw6"
   ----
   |  |->"fall"
   ----
   |  |->"spring"
   ----
   |  |->"autumn"
   ----
   |  |->"winter"
   ----

Lets decode this statement

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

Assume that on your platform sizeof(int) is 4 bytes, then this

ptr  = sizeof(int)  =>  ptr  = 4 

will make ptr pointing to string "autumn".

       ----
       |  |->"icsp"
       ----
       |  |->"hw6"
       ----
       |  |->"fall"
       ----
       |  |->"spring"
       ----
ptr--> |  |->"autumn"
       ----
       |  |->"winter"
       ----

Now, -2 subscript when applied to resulting pointer i.e. ptr[-2] will give the element before 2 index of current element, which is pointer to string fall. It will be assigned to ptr1. Printing ptr1 giving output fall.

CodePudding user response:

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);
  • Related