指针地址位置 [英] Pointers address location
问题描述
作为我们在编程语言学院培训的一部分,我们还学习了C.在测试期间,我们遇到了以下问题:程序输出将是什么:
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("\n");
return 0;
}
稍后,在检查了答案之后,很明显该单元(& ptr2)[3]与& ptr1 [2]中的存储单元相同,因此该程序的输出为:to be or not to be (Hamlet)
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.
推荐答案
在此语句中:
(&ptr2)[3] = str;
ptr2
是在main
中用char *ptr2
定义的.使用此定义,编译器负责为ptr2
提供存储.允许编译器为此使用所需的任何存储空间-可以在ptr1
之前,可以在ptr1
之后,可以很近,也可以很远.
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.
然后,&ptr2
使用ptr2
的地址.允许这样做,但是我们不知道该地址相对于ptr1
或其他任何位置,因为允许编译器使用所需的任何存储空间.
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.
由于ptr2
是char *
,所以&ptr2
是指向char *
的指针,也称为char **
.
Since ptr2
is a char *
, &ptr2
is a pointer to char *
, also known as char **
.
然后,(&ptr2)[3]
尝试引用位于&ptr2
的char *
数组的元素3.但是C的计算模型中没有数组.那里只有一个char *
.当您尝试在没有数组元素3的情况下引用数组元素3时,行为不是由C标准定义的.
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.
因此,此代码是一个错误的示例.看来测试作者误解了C,并且此代码并未说明预期的目的.
Thus, this code is a bad example. It appears the test author misunderstood C, and this code does not illustrate what was intended.
这篇关于指针地址位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!