What is the output of this code, array and pointers

136 Views Asked by At

I have a few questions regarding the code below.

  1. If I have a pointer of some type, what does it mean to use array indexing with it? in this example, what does ptr[3] stand for (ptr is a pointer of some type)?
  2. The output of the program is supposed to be to be or not to be (Hamlet) but I am not sure why, my problem is with the line (&ptr2)[3] = str, I don't understand how does this line changes the third element of the ptr1 array.

    int main()
    {
     char str[] = "hmmmm...";
     const char *const ptr1[] = {"to be", "or not to be", "that is the question"};
     char *ptr2 = "that is the question";
    
     (&ptr2)[3] = str;
    
     strcpy(str, "(Hamlet)");
     for (int i = 0; i < sizeof(ptr1) / sizeof(*ptr1); ++i)
     {
        printf("%s ", ptr1[i]);
     }
     return 0;
    }
    

Using this visualizer, we can see that ptr1 will point to str, I just don't understand why that happens.

Help appreciated.

1

There are 1 best solutions below

19
Govind Parmar On BEST ANSWER

If I have a pointer of some type, what does it mean to use array indexing with it? in this example, what does ptr[3] stand for (ptr is a pointer of some type)?

In C, a[i] is syntactic sugar for *(a + i). This is valid syntax for pointers, even if they aren't pointing to an array.

The output of the program is supposed to be to be or not to be (Hamlet) but I am not sure why, my problem is with the line (&ptr2)[3] = str, I don't understand how does this line changes the third element of the ptr1 array.

The line (&ptr2)[3] doesn't change anything in str1. It tries to access an unknown memory location.

If you were told that the output of this program is supposed to be "to be or not to be (Hamlet)", you were told wrong.