繁体   English   中英

“ unsigned int * ptr”和“ signed int * ptr”有什么区别?

[英]what is the difference between “unsigned int *ptr” and signed int *ptr"?

我知道整数指针将取消引用4个字节,然后对指针进行有符号和无符号处理? “ unsigned int * ptr”和“ signed int * ptr”是什么意思

指针类型表明它可以保留什么样的变量地址。 因此, unsigned int *ptr应该保留unsigned int地址,而signed int *ptr应该保留signed int地址。

请看下面的代码,

  int main()
  {
    unsigned int * ptr1;
    signed int * ptr2;

    unsigned int i;
    signed int s;

    ptr1 = &s;
    ptr2 = &i;

  }

它给我以下Visual Studio中的错误,

错误1错误C2440:'=':无法从'int *'转换为'unsigned int *'[...]

错误2错误C2440:'=':无法从'unsigned int *'转换为'int *'[...]

当你有

unsigned int* ptr;

假定ptr的值包含一个unsigned int 同样,当你有

signed int* ptr;

假定ptr的值包含一个有signed int

这是一个简单的实验:

#include <stdio.h>

int main()
{
   signed int i = -10;
   signed int* p1 = &i;
   unsigned int* p2 = (unsigned int*)p1;

   printf("Value of p1: 0x%p\n", p1);
   printf("Value of p2: 0x%p\n", p2);

   printf("Value of *p1: %d\n", *p1);
   printf("Value of *p2: %u\n", *p2);
}

该程序的示例输出:

Value of p1: 0x0x7fff1b52bd6c
Value of p2: 0x0x7fff1b52bd6c
Value of *p1: -10
Value of *p2: 4294967286

即使p1p2所保存的地址的数值相同,但在取消引用时,它们的取值也大不相同。

在C / C ++中,指针不过是一个内存位置。 对于给定的体系结构,它们的大小是相同的。 指针的类型(例如void *,int *,unsigned int *等)告诉编译器如何处理指针数学。

以这种方式可视化始终对我有帮助...

char *ptrMyString = "test";
int *ptrMyINTS[] = {1,2,3,4}

上面每个数组的内存如下所示:

Offsets        0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15 
ptrMyString = [t] [e] [s] [t] [0]
ptrMyINTS   = [0] [0] [0] [1] [0] [0] [0] [2] [0] [0] [0] [3] [0] [0] [0] [4]

sizeof(ptrMyString)应该等于sizeof(ptrMyINTS),因为它们只是内存指针。 但是,ptrMyString ++将增加1,而ptrMYINTS将增加4。

现在,我已经简化了很多事情,并忽略了诸如虚拟内存之类的东西,但是基本思想是,例如,如果两个指针都从0x00000000(32位地址)开始,则每个偏移量的指针值将为:

ptrMyString+0 = 0x00000000 = t
ptrMyString+1 = 0x00000001 = e
ptrMyString+2 = 0x00000002 = s
ptrMyString+3 = 0x00000003 = t

ptrMyINTS+0 = 0x00000000 = 1
ptrMyINTS+1 = 0x00000004 = 2
ptrMyINTS+2 = 0x00000008 = 3
ptrMyINTS+3 = 0x0000000C = 4

注意,所有位置的大小都相同,但我们增加的数量1和4分别来自指针的类型char *和int *。 我假设这里的int为4字节,因为它位于32位X86和ARM体系结构上。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM