为什么这是错误的,如指针在c [英] why this is wrong as per Pointer in c

查看:67
本文介绍了为什么这是错误的,如指针在c的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
#include <string.h>
int main()
{
int *p1, *p2;
int ar[2];

p1=&ar[0];
p2=&ar[1];

printf( "%d\n",p2 - p1); // this is right

printf( "%d\n",p2 + p1); // why this is wrong

    return 0;
}

推荐答案

第一个是通过取差来计算偏移量。此值可用于将现有指针递增n个值。它基本上是两个指针之间的项目数。



例如

The first one is calculating an offset by taking the difference. This value can be used to increment an existing pointer by n values. It is basically the count of items between the two pointers.

E.g.
p4 =  p3+(p2-p1);



有效,因为它会增加p3的数量p2和p1之间的项目。



如果另外加上两个指针,你将添加两个地址,指向远离你分配的内存位置数组并且肯定是一个错误。


is valid as it does increment p3 by the number of items between p2 and p1.

If you add on the other hand two pointers you are adding two addresses which will point to a memory location far far away in your allocated array and is definitely an error.


C 编程语言规范禁止添加指针,例如:ISO / IEC 9899:TC3pag。 82 [ ^ ]。
The C programming language specification forbids the addition of pointers, see, for instance: "ISO/IEC 9899:TC3" pag. 82[^].


第一个是正确的可能是巧合。你必须使用* p2 - * p1和* p2 + * p1



如果你写p1它得到它的地址
The first one is correct is a coincidence probably. You must use as *p2 - *p1 and *p2 + *p1

If you write p1 it gets its address


这篇关于为什么这是错误的,如指针在c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆