zoukankan      html  css  js  c++  java
  • 数组与指针的结合

    1.

    int main(int argc, char const *argv[])
    {
        int arr [5] = {0,1,2,3,4};
    
        int *p1 = &arr[0]; //P1指针表示指向arr数组的首地址
        int *p2 = arr;     //P2是数组首元素的地址
    
        printf("%d
    ",*p1);//取数组首元素的值
        printf("%p
    
    ",p1); //获取数组的地址值
    
        printf("%d
    ",*(p1 +1));//小括号优先级高,指针移动一个int的位置,然后取值
        printf("%d
    ",*p1 +10);//*优先级高,先获取数组的首元素的值为0,然后再+10
        printf("%d
    
    ",*(p1 +10));//指针越界,指针移动10个int到了未知的地址,获取到随机值
    
        printf("%p
    ",p2 );
        printf("%p
    ",p2 +1);//指针移动一个int
        printf("%d
    ",*p2 +1);//*p2获取到数组的第一个元素的值,为0;再+1等于1
    
        return 0;
    }
    

    2.数组指针,专门用来指向数组的指针

    #include <stdio.h>
    
    int main(int argc, char const *argv[])
    {
        //int *p; //定义一个名为p的指针
        //int (*p )[5] ;//该指针指向的类型为int [5],一个拥有五个元素的整型数组
    
        int arr [5] = {1,2,3,4,5};
        int (*p)[5] = &arr; //表示该指针指向arr数组的地址
    
        printf("%p
    ",arr);
        printf("%p
    ",*p);  //两个都是获取数组的首地址
    
        printf("%p
    ",*(p+1));//相当于获取数组中第二根元素的地址
        printf("%d
    ",(*p)[1]);//写成与定义一致来获取该数组中的第二个值
    
        printf("%p------%d
    ",p+1,(*(p+1)[2]));//越界访问
    
        return 0;
    }
    

    3.指针数组,专门用来存放指针的数组,就是指针数组

    #include <stdio.h>
    
    int main(int argc, char const *argv[])
    {
        int a = 1;
        int b = 2;
        int c = 3;
        int d = 4;
        int f = 5;
    
        int *p[10] = {&a,&b,&c,&d,&f,};
    
        for(int i = 0; i < 5;i++)
        {
            printf("%d
    ",*p[i]);//获取5个数组的值
            printf("%p
    ",p[i]);// 获取5个值对应的地址
        }
       
        printf("%p
    ",p[6]); //输出nil
        printf("%d
    ",*p[6]);//输出段错误,该数组第六个没有存放的地址,获取不到值
        
        return 0;
    }
    ![](https://img2020.cnblogs.com/blog/1742419/202105/1742419-20210509155532603-750112722.png)
    
    
  • 相关阅读:
    sqlserver监控体系
    使SQL用户只能看到自己拥有权限的库
    存储过程版本控制-DDL触发器
    查看剩余执行时间
    迁移数据库文件位置
    sublime使用Package Control不能正常使用的解决办法
    未在本地计算机上注册“Microsoft.Jet.OLEDB.4.0”提供程序的处理方式
    1770Special Experiment
    1848Tree
    1322Chocolate
  • 原文地址:https://www.cnblogs.com/hyxk/p/14747881.html
Copyright © 2011-2022 走看看