第12章学习笔记

1.关键字:auto,extern,static,register,const。。。
2.函数:rand,stand,time,malloc calloc,free
3.变量的作用域和生存周期
int giants = 5;  文件作用域,外部链接
static int dodgers = 3;//文件作用域,内部链接
intmain()
4.五种存储类

1)自动变量:
代码块作用域和空连接意味着只有变量定义所在的代码块才可以通过名字访问该变量。
自动周期意味着当程序进入包含变量声明的代码块的时候,变量才是存在,当离开之后,释放,所占内存可以被占用。
实例:

不带{}的代码块 :for,while,if等只有一个语句时候可以不加{}。


2) 寄存器变量register
一般来说,变量存储在计算机内存中。如果幸运的话,寄存器变量可以存储在cpu寄存器中;目的是为了更快的被访问和操作。该变量无法获得寄存器的地址。
3)具有代码块作用域的静态变量
静态:变量的存储位置保持不动。当包含该静态变量的函数完成工作之后,该变量所在的地址并不会被释放。从一次函数调用到下一次的函数调用,计算机都记录着他们的值。通过static在函数中声明创建。
#include <stdio.h>


void trystat(void)
{
    int fade = 1;
    static int stay = 1;
    
    printf("fade is %d  and stay is %d \n",fade++,stay++);


}


int main(int argc, const char * argv[])
{
    int i = 10;
    while(i-- >0)
    trystat();
    
    
    printf("Hello, World!\n");
    return 0;
}
fade is 1  and stay is 1 
fade is 1  and stay is 2 
fade is 1  and stay is 3 
fade is 1  and stay is 4 
fade is 1  and stay is 5 
fade is 1  and stay is 6 
fade is 1  and stay is 7 
fade is 1  and stay is 8 
fade is 1  and stay is 9 
fade is 1  and stay is 10 
Hello, World!


4)具有外部变量的静态变量。extern
把变量的定义生命在所有的函数之外,即创建了一个外部变量。


5.随机数函数和静态变量。
1)种子:
//
//  main.c
//  randAnnTime
//
//  Created by lichan on 13-10-16.
//  Copyright (c) 2013年 lichan. All rights reserved.
//


#include <stdio.h>


#include <time.h>


static unsigned long int next = 1;
void srand1(unsigned int x)
{
    next = x;
    
}


extern int rand1(void)
{
    next = next *1103515245 +12345;
    
    return (unsigned int) (next/65536)%32768;


}


//产生一个sides范围之内的随机数


int rollem(int sides)
{
   
    
    return rand1()%sides +1;




}




int main(int argc, const char * argv[])
{
    int count;
   
    for (count = 0; count <5; count++) {
        printf("%d\n",rand1()) ;
    }
    printf("--------------");
    for (count = 0; count <5; count++) {
        printf("%d\n",rand1()) ;
    }
  
       printf("--------------\n");
    for (count = 0; count <4; count++)
   printf("the roll is %d\n",rollem(6)) ;
    
    
    
    return 0;
}


6.内存分配:malloc 和free


1)使用malloc函数建立一个数组。
   double *pt;
pt = (double*)malloc(30*sizeof(double));
2)free的重要性。

3)calloc()函数  与 malloc函数类似。


  long *newmen;
newsmen = (long*0 calloc(100,sizeof(long));
malloc特性:它将块中得所有位置都置0.





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值