指针与结构体

第九周备课——

关于指针的注意事项

1.1____定义(一)

int* a;
int *a;
int *a,b;
int* a,b;

1.2____定义(二)

int a[10] = {0,1,2,3,4,5,6,7,8,9};
int *p1 = a;
int *p2 = &a;
int *p3 = &a[0];

1.3____区别

int a[10] = {0,1,2,3,4,5,9,11,15,20};
int* p = &a;
cout << *(p++) << endl;
cout << *p++ << endl;
cout << *++p << endl;
cout << *p++ << endl;
cout << *(++p) << endl;
cout << (*p)++ << endl;
cout << ++(*p) << endl;

++(自增运算符)的优先级高于 * (解引用运算符)


一、指针的颠倒

#include <bits/stdc++.h>
#include <time.h>
#include <stdlib.h>
using namespace std;

clock_t start,stop;
///颠倒数组的指针做法一

const int maxn = 100;

void print(int *a, int size)    ///打印这个数组
{
    for(int i = 0; i < size ; i++){
        cout << i<< "\t";
    }
    cout << endl;
    for(int i = 0; i < size ; i++){
        cout << *a << "\t";     ///不能写成(*a)++
        a++;
    }
    cout << endl;
}

void init(int *a,int size)
{
    for(int i = 0; i <size ; i++){
        *a = rand() % maxn;
        a++;
    }

}

void myReverse(int *a,int size)
{

    for(int i = 0 ; i < size/2; i++){
        int temp = a[i];
        a[i] = a[size - i - 1];
        a[size - i - 1] = temp;

    }

}

int main()
{
    int *p;
    srand((unsigned)time(NULL)); ///

    int size = 10;

    start = clock();

    init(p,size);
    print(p,size);
    myReverse(p,size);
    cout << endl;
    print(p,size);

    stop = clock();

    cout << "the time spend : " << (double)(stop - start) / CLK_TCK;

    return 0;
}

二、指针和字符串

字符指针相当于字符串

字符指针的初始化


指针都要分配内存!

分配方式一: 指向

char s[10];
char* p = &s;
char* p = " ~LSNUACM~ ";

分配方式二: 动态内存分配

char* s = new char[10];
char* s = (char *)malloc( sizeof(char) * 10 );

三、结构体

结构体的定义

struct node{
    
}name1,name2[10];

typedef node{

}name1,name2[10];

结构体的初始化

int main()
{
    struct node a = {};
}

指向结构体的指针


posted @ 2020-12-12 18:38  Hoppz  阅读(246)  评论(0编辑  收藏  举报