2012-02-29 104 views
1

我想了解指针和数组。奋力网上找到指针(双关语!)之后,我说明我的困惑在这里..指针和数组混淆

//my understanding of pointers 
int d = 5; //variable d 
int t = 6; //variable t 

int* pd; //pointer pd of integer type 
int* pt; //pointer pd of integer type 

pd = &d; //assign address of d to pd 
pt = &t; //assign address of d to pd 

//*pd will print 5 
//*pt will print 6 

//My understanding of pointers and arrays 

int x[] = {10,2,3,4,5,6}; 
int* px; //pointer of type int 

px = x; //this is same as the below line 
px = &x[0]; 
//*px[2] is the same as x[2] 

到目前为止,我得到它。现在,当我执行以下操作并打印pd [0]时,它会显示出类似-1078837816的内容。这里发生了什么?

pd[0] = (int)pt; 

任何人都可以帮忙吗?

回答

1

INT *磅;是一个指向整数类型变量的指针,它不是一个整数。通过指定(int)pt,您告诉编译器将typecast pt设置为整数。

要获得pt处的变量,您可以使用* pt,这会返回存储在pt中的地址指向的整数变量。

因为你说pd [0],而pd不是数组,所以有点令人困惑。

+0

在这种情况下,我在阅读:“http://www.osdever.net/tutorials/view/implementing-basic-paging”。 “设置页表”部分声明一个无符号的long * page_table,然后在for循环中使用page_table [i]。但page_table不是一个数组,所以我很困惑,为什么它会这样使用。你能解释一下吗? – rgamber 2012-02-29 06:59:30

+1

数组本质上是指向顺序存储器的指针,数组中的每个元素都是指针变量类型的大小。在那个例子中,他们创建了一个从内存中的特定点开始的无符号长指针(4字节),然后循环1024次,基本上覆盖了4096字节的内存。数组的每个增量都是内存中的下一个无符号长整数。 – 2012-02-29 07:05:00

+0

对不起,但我很困惑,如何将无符号长指针变量用作数组。你说“数组的每个增量是内存中的下一个无符号long”,但是这里没有声明数组。谢谢您的帮助。 – rgamber 2012-02-29 07:15:07

1

您已经告诉编译器将指针pt的字节解释为int,因此您将看到一个看似随机的结果,表示pt碰巧位于内存中的任何位置。

我想你想

pd[0] = pt[0] 

pd[0] = *pt;