这一点在哪里 [英] Where will this point
问题描述
以前我被问过这个问题并且不确定给出的确切答案,
想象我有:
(& x- 99 )[ 2 ]
问题是,它指向哪里?
我的初步解释是,因为我们不知道哪个存储区域和放大器; x-99将结束,
编译器/程序可能不知道确切地知道它有多少字节,通过查看[2]向前推进。
是我对吗?例如,如果我们向int指针添加1,它将向前移动4个字节,如果我们向char指针添加1它将向前移动一个字节,...
ps。我看到没有人在这里理解我的问题。我说,有y [2](y是int)。
现在,编译器如何计算偏移量?它可能需要y类型并添加8(8 = 4 * 2)
对吗? (由于int的大小)。现在在这种情况下:(& x-99)[2]。我的问题是,这里有什么补偿?编译器需要多少字节并乘以2?在前一种情况下,它检查了y的类型,但在这种情况下,它如何知道哪种类型(& x-99)对应?我现在说清楚了吗?
试试这段代码:
#include < iostream >
#include < vector >
使用 命名空间标准;
int main()
{
int x [ 1000 ];
int (* p)[ 1000 ] =& x- 99 跨度>;
cout<< x<< ,<< p << ,<< p [ 2 ]<< ENDL;
cout<< ( int )(& x-p)<< ,<< ( int )(x-p [ 2 ])<< ENDL;
}
我的系统输出:
< pre lang =c ++> 019DEDC0,0197E2E0, 01980220
99 , 97000
C ++是强类型语言。您的示例是指针运算的简单情况。 99将乘以x类型的字节数。为了说明,这是一个例子:
int main()
{
int 到达[ 10 ] = { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 < /跨度>};
char arrc [ 10 ] = {' 0',' 1',' 2',' 3',' 4',< span class =code-string>' 5',' 6',' 7',' 8',' 9 跨度>};
std :: cout<< Int ptr:<< (&到[ 0 ] + 1 )[ 2 ]<< \ n;
std :: cout<< Char ptr:<< (& arrc [ 0 ] + 1 )[ 2 ]<< \ n;
return 0 ;
}
Previously I was asked this question and was not sure about the exact answer to give,
imagine I have:
(&x-99)[2]
The question was, where would it point?
My initial explanation was that since we don't know in which memory region &x-99 will end up,
the compiler/program might not know exactly, how many bytes from it, to move forward by looking at [2].
Was I right? e.g., if we add 1 to a int pointer, it will move say 4 bytes forward, if we add 1 to char pointer it will move one byte forward, ...
ps. I see nobody understood my question here correctly. I was saying, say there is y[2] (y is int).
Now, how does compiler calculate offset? it takes probably type of y and adds to it 8(8=4*2)
right? (due to size of int). Now in this case: (&x-99)[2]. My question was, what will be the offset here? How many bytes should compiler take and multiply on 2? In previous case it checked type of y, but in this case, how does it know which type (&x-99) corresponds to? Did I make it clear now?
Try this code:
#include <iostream> #include <vector> using namespace std; int main() { int x[1000]; int (*p)[1000] = &x-99; cout << x << ", " << p << ", " << p[2] << endl; cout << (int)(&x-p)<< ", " << (int)(x-p[2]) << endl; }
output on my system:
019DEDC0, 0197E2E0, 01980220 99, 97000
C++ is strongly typed language. Your example is simple case of pointer arithmetic. "99" will be multiplied by number of bytes of size of type "x". To illustrate, here is an example:
int main() { int arri[10] = {0,1,2,3,4,5,6,7,8,9}; char arrc[10] = {'0','1','2','3','4','5','6','7','8','9'}; std::cout << "Int ptr:" << (&arri[0] + 1)[2] << "\n"; std::cout << "Char ptr:" << (&arrc[0] + 1)[2] << "\n"; return 0; }
这篇关于这一点在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!