指针基础(此文还没涉及指针作为函数形参)

来源:互联网 发布:ct图像重建算法matlab 编辑:程序博客网 时间:2024/06/06 05:44
#include<iostream>using namespace std;/*指针  ----  指向一个地址( &  NULL  0    )*/int main(){    int a = 1;    //int *p = &a;-----第一种初始化    //第二种初始化    int *p;    p = &a;    a += 3;    *p += 3;    cout << a << endl;//  结果为7    return 0;}

我学的时候就有一个疑问:*p的初始化是个地址,cout << *p << endl;输出时是个数据,cout << p << endl;这个输出是就是个地址,我也是搞不懂,只能是记着了

#include<iostream>using namespace std;/***数组 类似 指针**  */int main(){    int a[] = { 1,2,5,8,7,8,2 };    int *p = a;     //指针指向a    //*p == *a 默认指向数组的第一位---0    cout << *p << endl;         // 1    cout << *a << endl;         // 1    p = &a[4];    cout << *p << endl;         // 7    //指针加法运算   *p2 = p + 4  == p2[4]    int *p2 = p + 4;            //5+4 > a数组元素个数    cout << *p2 << endl;    //下溢  越界    //指针减法运算    ptrdiff_t n = p2 - p;    //ptrdiff_t是C++库中的,就是typedef int ptrdiff_t    cout << n << endl;    int first = *a+4;       //1 + 4 =5  4是个数值    cout << first << endl;    int last = *(a + 4);        //7   4代表的是数组加上4后的位置    cout << last << endl;    //a[] = { 1,2,5,8,7,8,2 };    int *p3 = &a[2];    int i = p3[2];    cout << *p3 << endl;  //5    //例子--遍历    const size_t arr_sz = 10;    int int_arr[arr_sz] = { 0,1,2,5,4,6,32,54,12,4 };    for (int *p = int_arr,*q = int_arr + arr_sz; *p != *q; *p++)    {        cout << *p << endl;    }    return 0;}
原创粉丝点击