//
// main.m
// C9_内存管理
//
// Created by YIem on 15/11/20.
// Copyright (c) 2015年 www.yiem.net YIem博客. All rights reserved.
//

import <Foundation/Foundation.h>

void staticFunc();
void staticFunc() {

// 定义静态变量
// 1.静态变量 只会赋值一次初值
// 2.默认赋值初值为0
static int a = 10;
a++;
printf("%d\n", a);

}

int main(int argc, const char * argv[]) {

// 内存管理
// 栈                   自动区
// 堆                   动态区
// 全局静态              静态区
// 常量
// 代码

if 0

int a = 100;
printf("stack.......%p\n", &a);
// 堆  malloc
int *p = malloc(8);
printf("malloc......%p\n", p);
// 全局静态 static
static int b = 100;
printf("static......%p\n", &b);
// 常量 constant
char *s = "abc";
// s[0] = 'i'; // 错误 常量字符串不能被改变
printf("constant....%p\n", s);
// 代码 func
printf("func........%p\n", main);

// static 静态修饰

staticFunc();
staticFunc();
staticFunc();
// 常量修饰
// 将变量变为只读 不允许修改
// 将变量变为只读 不允许修改 用于保护数据
const int c = 10;
//c = 20;

endif

if 0



// 堆内存操作函数
// 开辟堆内存空间 在堆内存中开辟一段size大小的内存空间 返回首地址(void *)
// void * 无类型指针 可以由任意类型指针接收 接收类型即为操作类型
// malloc 函数名
// unsigned long size 空间大小
// void *malloc(unsigned long size)
int *p = malloc(8);
// 空间大小 = 类型大小 * 个数
int *p1 = malloc(sizeof(int) * 5);
// 堆区内存空间 当做数组使用
// 随机赋值
for (int i = 0; i < 5; i++) {
    *(p1 + i) = arc4random() % 11;
    printf("%d ", *(p1 + i));
}
// 冒泡
printf("\n");
for (int i = 0; i < 5 - 1; i++) {
    for (int j = 0; j < 5 - 1 - i; j++) {
        if (*(p1 + j) > *(p1 + j + 1)) {
            int temp = *(p1 + j);
            *(p1 + j) = *(p1 + j + 1);
            *(p1 + j + 1) = temp;
        }
    }
}
for (int i = 0; i < 5; i++) {
    printf("%d ", *(p1 + i));
}
printf("\n");

// 回收堆内存  // 用完回收
free(p1); // 一个值能还一个
//free(p1); // 过度释放
free(p);

endif

if 1

// 字符串
char *str = malloc(sizeof(char) * 10);
strcpy(str, "iPhone");
printf("%s\n", str);
printf("%lu\n", strlen(str));
// 练习: 有一个字符串,其中包含 数字,提取其中的数字,要求动态分配内存保存
char *string = "a1b2c33d545";
char *s = string;
int count = 0; // 数字个数
while (*s) {
    if (*s >= '0' && *s <= '9') {
       // 如果为数字 count++
        count++;
    }
    // 继续读取下一个字符
    s++;
}
char *num = malloc(count + 1);
int i = 0, j = 0;// 分别控制源字符串下标和数字字符串下标
while (*(string + i)) {
    if (*(string + i) >= '0' && *(string + i) <= '9') {
        *(num + j) = *(string + i);
        j++;
    }
    i++;
}
*(num + j) = '\0';
printf("%s\n", num);



endif


















return 0;

}