我第一次学习C语言指针和地址,以及如何在我的平板电脑上使用它们。
假设:
int x = 1, y = 2;
int *ip; // declares *ip as an int type?
ip = &x; //assigns the address of x to ip?
y = *ip; //y is now 1 via dereferencing
这些注释的解释是否都正确?
如果我打印IP的结果会发生什么?它会打印变量X的地址,类似于
011001110
int *ip;
更好的说法是ip
是指向int
类型的指针。
如果我打印
ip
的结果会发生什么?
它将打印x
的地址。
它会打印变量x的地址吗,类似于
011001110
地址通常以十六进制表示。您应该使用%p
说明符来打印地址。
printf("Address of x is %p\n", (void *)ip);
注意:
请注意,在上面的声明中,*
不是间接运算符。相反,它指定了p
的类型,告诉编译器p
是一个指向int
的指针。当*
出现在语句中时,该符号才执行间接寻址操作。
*
不是解引用运算符。 - haccksint x = 1, y = 2;
int *ip; // declares ip as a pointer to an int (holds an address of an int)
ip = &x; // ip now holds the address of x
y = *ip; // y now equals the value held at the address in ip
初始化器 x y ip 内存值 [1] [2] [1000] 内存地址 1000 1004 1008如您所见:
x
的值为 1
,地址为 1000
y
的值为 2
,地址为 1004
ip
的值为 1000
(即 x
的地址),地址为 1008
x == 1
,&x == 1000
y == 2
,&y == 1004
ip == 1000
,&ip == 1008
,*ip == 1
(即 x
的值)一切都正确。
第一行:您声明了两个变量
第二行:定义了一个内存指针“ip”
第三行:将X的内存地址赋给指针ip
第四行:现在,Y被设置为地址ip处变量X的值
然而,内存地址是十六进制格式。011001110是数据字节,不是内存地址。地址更可能是类似于0x000000000022FE38(可能会更短)。请考虑这一点:
int x = 0;
int *ptr = &x; //the "&" character means "the address of"
printf("The variable X is at 0x%p and has the value of %i", (void *)ptr, x);
*ip
是一个int
。这准确地反映了声明的语义,其中声明符*ip
是一个表达式,而声明说明符(在本例中为int
)提供表达式的类型。以这种方式陈述含义可以深入了解像int *ip, q;
这样的东西的含义,其中q
只是一个简单的int
。你可能不想在交谈中使用这种更正式的类型陈述方式,但它有助于看到声明所表达的基本结构。std::cout
。int x = 1;
int* y = &x;
std::cout << "The address of x is " << &x << std::endl
<< " and is also " << y << std::endl;
The address of x is 0x7ffe9eb117e4
and is also 0x7ffe9eb117e4
ip
,是的,你会得到x
的地址。地址的格式取决于你用来打印它的格式字符串。你可以用十进制、十六进制或其他格式来写它。 - lurker