对于基本数据类型,指针如何在C中递增? 我无法理解为什么下面的代码中的差异没有给出我在内存位置的字节差异,它正在给我1 ..
Here is my code::
char c1='c';
char *c=&c1;
int i1=1;
int *i=&i1;
long l1=1;
long *l=&l1;
float f1=1.1;
float *f=&f1;
double d1=1.3;
double *d=&d1;
printf("c =%u ,c +1=%u\n",c,c+1);
printf("i =%u ,i +1=%u\n",i,i+1);
printf("l =%u ,l +1=%u\n",l,l+1);
printf("f =%u ,f +1=%u\n",f,f+1);
printf("d =%u ,d +1=%u\n",d,d+1);
printf("c diff =%u\n",(c+1)-(c));
printf("i diff =%d\n",(i+1)-(i));
printf("l diff =%u\n",(l+1)-(l));
printf("f diff =%u\n",(f+1)-(f));
printf("d diff =%u\n",(d+1)-(d));
printf("c diff =%u\n",(c)-(c+1));
printf("i diff =%u\n",(i)-(i+1));
printf("l diff =%u\n",(l)-(l+1));
printf("f diff =%u\n",(f)-(f+1));
printf("d diff =%u\n",(d)-(d+1));
Output::c =1636923 ,c +1=1636924
i =1636896 ,i +1=1636900
l =1636872 ,l +1=1636876
f =1636848 ,f +1=1636852
d =1636820 ,d +1=1636828
c diff =1
i diff =1
l diff =1
f diff =1
d diff =1
c diff =4294967295
i diff =4294967295
l diff =4294967295
f diff =4294967295
d diff =4294967295
Why I am not getting "i diff =%d\n",(i+1)-(i) ==>> 4
答案 0 :(得分:1)
这里有几件事:当你进行指针运算时,你不处理字节,你正在处理X * sizeof(pointertype)。当你说(i + 1)-i时,你没有做“多少字节”的操作,而是取回两点之间指针位置的数量。这是指针位置的差异。
答案 1 :(得分:1)
指针算法总是以指向类型为单位。这不仅意味着p + 1
在内部将sizeof(*p)
添加到内存地址(这是您在前4行中看到的内容),而且p - q
会告诉您有多少项位于两个指针之间,而不是有多少个字节。最后四个数字大约为40亿,因为用于这些计算的类型是无符号的,因此下溢:p+1
大于p
,因此p - (p+1)
将为负数。
答案 2 :(得分:1)
我无法理解为什么以下代码中的差异不会给我带来差异
因为没有指定这样做。
它正在给我一个
如果你将X加1并减去X,你就会回来1.这是一个算术定律。 C具有“指针算术”并且它遵守算术定律(如果定义了所讨论的操作)。这里没什么大惊喜。
答案 3 :(得分:1)
Why I am not getting "i diff =%d\n",(i+1)-(i) ==>> 4
因为在大多数情况下它都是这样的:
(i+1) - (i) / sizeof(int)
等于1.
但是你应该注意到,这没有定义,如C标准中所引用的那样,指针减法工作时指针应该指向同一个数组中的元素或者超出它:
来自C11标准(6.5.6第9段)
当减去两个指针时,两个指针都应该指向 相同的数组对象,或者超过数组对象的最后一个元素; 结果是两个数组的下标的差异 元件。