Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

As part of our training in the Academy of Programming Languages, we also learned C. During the test, we encountered the question of what the program output would be:

#include <stdio.h>
#include <string.h>

int main(){
    char str[] = "hmmmm..";
    const char * const ptr1[] = {"to be","or not to be","that is the question"};
    char *ptr2 = "that is the qusetion";

    (&ptr2)[3] = str;

    strcpy(str,"(Hamlet)");
    for (int i = 0; i < sizeof(ptr1)/sizeof(*ptr1); ++i){
        printf("%s ", ptr1[i]);
    }
    printf("
");
    return 0;
}

Later, after examining the answers, it became clear that the cell (& ptr2)[3] was identical to the memory cell in &ptr1[2], so the output of the program is: to be or not to be (Hamlet)

My question is, is it possible to know, only by written code in the notebook, without checking any compiler, that a certain pointer (or all variables in general) follow or precede other variables in memory?

Note, I do not mean array variables, so all the elements in the array must be in sequence.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
123 views
Welcome To Ask or Share your Answers For Others

1 Answer

In this statement:

(&ptr2)[3] = str;

ptr2 was defined with char *ptr2 inside main. With this definition, the compiler is responsible for providing storage for ptr2. The compiler is allowed to use whatever storage it wants for this—it could be before ptr1, it could be after ptr1, it could be close, it could be far away.

Then &ptr2 takes the address of ptr2. This is allowed, but we do not know where that address will be in relation to ptr1 or anything else, because the compiler is allowed to use whatever storage it wants.

Since ptr2 is a char *, &ptr2 is a pointer to char *, also known as char **.

Then (&ptr2)[3] attempts to refer to element 3 of an array of char * that is at &ptr2. But there is no array there in C’s model of computation. There is just one char * there. When you try to refer to element of 3 of an array when there is no element 3 of an array, the behavior is not defined by the C standard.

Thus, this code is a bad example. It appears the test author misunderstood C, and this code does not illustrate what was intended.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...