C:指针运算 - 如何操作呢? [英] C:Pointer Arithmetic -How does it work?

查看:149
本文介绍了C:指针运算 - 如何操作呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的C语言编程,并试图了解指针运算工作。下面的printf语句打印2时printf的参数是*(P + 2)和4与* P。能否请您解释这种现象?

 的#include<&stdio.h中GT;
#包括LT&;&CONIO.H GT;诠释的main()
{
    INT ARR [4] = {4,3,2,1},* P =改编;
    的printf(\\ N%D,*(P + 2));    返回0;
}


解决方案

让我们重新编写程序,以使其更清晰一点:

 #包括LT&;&stdio.h中GT;INT主要(无效)
{
    INT ARR [4] = {4,3,2,1};
    为int * p =改编;
    的printf(\\ N%D,*(P + 2));
    返回0;
}

现在, *(P + 2)是定义相同的 P [2] 。由于 P 的ARR的第一个元素,那么 P [2] 相同改编[2] 等于 2

同样, *(P)相同 * P ,自改编点的第一个元素,则 *(p) 4

您可能需要重新读你的文字书,涵盖指针运算的部分。

I'm new to C programming and trying to understand how pointer arithmetic works. The below printf statement prints 2 when the arguments for printf is *(p+2) and 4 with for *p. Could you please explain this behaviour ?

#include <stdio.h>
#include <conio.h>

int main()
{
    int arr[4] = {4,3,2,1}, *p = arr;
    printf("\n%d", *(p+2));

    return 0;
}

解决方案

Let's re-write your program to make it a little clearer:

#include<stdio.h>

int main(void)
{
    int arr[4] = {4,3,2,1};
    int *p = arr;
    printf("\n%d", *(p+2));
    return 0;
}

Now, *(p+2) is by definition the same as p[2]. Since p points to the first element of arr, then p[2] is the same as arr[2] which is equal to 2.

Similarly, *(p) is the same as *p and since p points to the first element of arr then *(p) is 4.

You probably need to re-read the section in your text book that covers pointer arithmetic.

这篇关于C:指针运算 - 如何操作呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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