C语言程序设计:现代方法(11-13章)

第11章 指针

每个字节byte(8位)都有唯一的地址。

  • *用来定义指针变量: int *p,对应的表达式 *p 表示指针变量指向的地址中存放的内容
  • &运算用来获取变量的指针(地址),p = &i
  • 这里 i 和 *&i 是相等的
  • *p=j是把对应地址的值修改位j
  • scanf 中的参数实际就是指针
#include <stdio.h>
#include <time.h>
#define _CRT_RAND_S   // rand_s depends on the RtlGenRandom API, which is only available in Windows XP and later.
#include <stdlib.h>

int main() {
    int i,*p;
    p=&i;
    printf("请输入一个整数:");
    scanf("%d",p);
    printf("%d",i);
    return 0;
}

/*
请输入一个整数:10
10
*/

求数组中的最大值最小值:

#include <stdio.h>

int max_min(int n, int arr[n], int *the_max, int *the_min) {
    *the_max = arr[0]; // 把big变量对应的值修改
    *the_min = arr[0];
    for (int i = 1; i < n; i++) {
        if (arr[i] > *the_max) {
            *the_max = arr[i];
        }
        if (arr[i] < *the_min) {
            *the_min = arr[i];
        }
    }
}

int main() {
    int arr[] = {3, 2, 1, 9, 4, 5, 6, 7, 8}, big, small;
    // 传入了big和small连个变量的指针,用来保存回调的变量
    max_min(9, arr, &big, &small);
    printf("big = %d\n", big);
    printf("small = %d\n", small);
    return 0;
}

/*
big = 9
small = 1
*/

第12章 数组

数组名为指向数组第一个元素的指针。

#include <stdio.h>

void print_array(int *arr,int size) {
    for (int i = 0; i < size; i++) {
        printf("%3d", arr[i]);
    }
    printf("\n");
}

int main() {
    int arr[] = {3, 2, 1, 9, 4, 5, 6, 7, 8};
    int size = sizeof(arr) / sizeof(arr[0]);
    print_array(arr, size);
    *arr=0;
    *(arr+1)=1;
    print_array(arr, size);
    return 0;
}

/*
  3  2  1  9  4  5  6  7  8
  0  1  1  9  4  5  6  7  8
*/

正文完
 0
评论(没有评论)