DAY6

发布时间 2023-07-28 15:51:08作者: Ninnne

指针练习

  1. 声明变量:pstr是一个指向数组的指针,该数组内含20个char类型的值

 char (*pstr)[20];
  1. 编写一个函数,返回储存在int类型中数组中的最大值,并在一个简单的程序中测试该函数

#include <stdio.h>
int get_max(int number[],int n){
    int max = number[0];
    int i;
    for(i=0;i<n;i++){
        if(max<number[i]){
            max = number[i];
        }
    }
    return max;
}
int main(void){
    int source[100] = {1,2,3,4,5};
    printf("The largest number in array is %d",get_max(source,100));
    return 0;
    
}

输出结果:

The largest number in array is 5

内存泄漏

内存泄漏指的是我们动态申请了内存(heap),但是即使是使用完了之后也不去释放它

  1. 一个赌博游戏

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int cash = 100;//用来储存现金 
void play(int bet){
    char C[3] = {'J','Q','K'};
    printf("Shuffling ...");//正在洗牌 
    srand(time(NULL));//根据时间给出的随机数 
    int i;
    for(i = 0;i<5;i++){
        int x = rand() % 3;//用rand()生成一个随机数,随机数在0-3之间 
        int y = rand() % 3;
        int temp = C[x];
        C[x] = C[y];
        C[y] = temp;//交换这些位置上的字符 
        
    }//两个位置的字符进行了交换,执行五次,每次随机数选择两个位置x和y 
    int playersguess;
    printf("What's the position of queen - 1,2 or 3?"); 
    scanf("%d",&playersguess);
    if(C[playersguess-1] == 'Q'){
        cash += 3*bet;
        printf("You Win ! Result = \"%c %c %c\" Total Cash = %d\n",C[0],C[1],C[2],cash);
        
    }else{
        cash -=bet;
        printf("You Loose ! Result = \"%c %c %c\" Total Cash = %d\n",C[0],C[1],C[2],cash);
    }
}
​
int main(){
    int bet;
    printf("Welcome to the Vitrual Casino\n");
    printf("Total cash = $%d\n",cash);
    while(cash>0){
        printf("What's your bet? $");
        scanf("%d",&bet);
        if(bet == 0 || bet > cash){
            break;
        }
        play(bet);
        printf("\n****************************\n") ;
    }
} 
​

输出:

Welcome to the Vitrual Casino
Total cash = $100
What's your bet? $5
Shuffling ...What's the position of queen - 1,2 or 3?3
You Loose ! Result = "Q J K" Total Cash = 95
​
****************************
What's your bet? $

我们不论玩多少次,应用程序的内存的不会变(没有明显增长,因为储存在栈(stack)中,用一次就会清理一次

  1. 当把paly函数的局部变量也就是特定数组C[ ]在堆上分配内存

char *C = (char*)malloc(3*sizeof(char));
    C[0] = 'J'; C[1] = 'Q'; C[2] = 'K'; 

这样我们就在堆上创建了一个数组,C就是这个数组的基地址,C还是一个局部变量,但是现在它是一个字符指针

随着游戏次数多增加,应用程序的内存也不断增加

  1. 内存泄漏总是因为堆中未使用和未引用的内存块才发生的,栈上的内存是自动回收的,栈的大小是固定的,最多的就是发生栈溢出