c 指针详解与应用

简介

 

存储机制

 

 详解:

  • int a  = 0x12345678;
  • 在内存中拆分成 0x12、0x34、0x56、0x78
  • 先存小的0x78,依次到0x12.这种存储称为:小端存储

 

定义指针

 

 详解:

  • (unsigned)char : char 型 或者unsigned char型 占1个字节, 指向它的指针为: 16位系统:2个字节; 32位的:4个字节;  64位的: 8个字节.
  • 指针的占用大小与系统有关。

 

操作

 

示例:

 

#include <stdio.h>

int main(){
  int a[] = {0x11, 0x22, 0x33};
  printf("%x\n", a[0]);
  printf("%x\n", sizeof(a[0]));
  // 每次+1都次移动4个字节位
printf(
"%x\n", a[0+1]); printf("%x\n", sizeof(a[0+1])); printf("%x\n", a[0+1+1]); printf("%x\n", sizeof(a[0+1+1])); }

 

数组与指针

 

示例:

#include <stdio.h>
#include <stdlib.h>

int main(){
  int a[] = {0x11, 0x22, 0x33};
  // int a[] = {0x11, 0x22, 0x33};
  // 等价于
  /*
  int *a;
  a = malloc(3*4);
  a[0] = 0x11;
  a[1] = 0x22;
  a[0] = 0x33;
  */

  printf("a[0]:%x\n", a[0]);
  printf("a[1]:%x\n", a[0]);
  printf("a[2]:%x\n", a[0]);

  // 等价于
  printf("*a[0]:%x\n", *a);
  printf("*a[1]:%x\n", *(a +1));
  printf("*a[2]:%x\n", *(a + 2));

}

 注意

 

C 指针应用

 

 使用同一源数据:

#include <stdio.h>

void editMax(int *array)
{
    array[1] = 1000;
}

int main()
{
    int a[] = {1,2,3,4,5,6};
    printf("a[1]: %d\n", a[1]);
    editMax(a);
    printf("a[1]: %d\n", a[1]);

}

 

返回多个参数示例:

#include <stdio.h>


void funcMaxAndCount(int *max, int *count, const int *array, int length)
{
    int i;
    *count = 1;
    *max = array[0];
    for (i=1; i<length; i++)
    {
        if (array[i] > *max){
            *max = array[i];
            *count=1;
        }else if (array[i] == *max){
            (*count)++;
        }
    }
}

int main()
{
    /*  Write C code in this online editor and run it. */
    printf("Hello, World! \n");
    int a[] = {6,5,3,4,5,6,4,6};
    int Max;
    int Count;
    
    funcMaxAndCount(&Max, &Count, a, 8);
    
    printf("%d\n", Max);
    printf("%d\n", Count);
    return 0;
}

 

使用“句柄”操作:

#include <stdio.h>


/*********************/
int Time[] = {11,22,33};

void *editMax()
{
    return Time;
}
/********************/

int main()
{
    printf("Time[0]: %d\n", Time[0]);
    printf("Time[1]: %d\n", Time[1]);
    printf("Time[2]: %d\n", Time[2]);
    int *time;
    time = editMax();
    printf("time[0]: %d\n", time[0]);
    printf("time[1]: %d\n", time[1]);
    printf("time[2]: %d\n", time[2]);
}

 

视频:

https://www.bilibili.com/video/BV1Mb4y1X7dz?spm_id_from=333.337.search-card.all.click&vd_source=a535a5f8decab718e4474242fc8a5efd

 

posted @ 2022-07-17 17:11  萤huo虫  阅读(51)  评论(0编辑  收藏  举报