指针与动态数组
来源:互联网 发布:淘宝主图怎么弄吸引人 编辑:程序博客网 时间:2024/06/08 06:15
C语言中如何实现动态数组:
- 使用malloc()库函数(内存分配)来得到一个指向一大块内存的指针;
- 像引用数组一样引用这块内存
如果需要使数组有动态增长的能力,那就修改内存的总容量,直接在运行时在堆上分配数组的内存。这就用到库函数realloc(),它能够对一个现在的内存块大小进行重新分配(通常是实质扩大),同时不会丢失原先内存块的内容。
#include <arpa/inet.h>#include <netinet/in.h>#include <stdio.h>#include <stdlib.h> // exit()int current_element = 0;int total_element = 4;char *dynamic = NULL;int add_element(char c) { if (current_element == total_element) { total_element *= 2; char *test = (char *)realloc(dynamic, total_element); if (test == NULL) { printf("error\n"); return 0; } dynamic = test; } dynamic[current_element++] = c; return 1;}int main(int argc, char **argv) { dynamic = malloc(total_element); dynamic[current_element++] = 'a'; dynamic[current_element++] = 'b'; dynamic[current_element++] = 'c'; char c = 'd'; if (add_element(c) == 1) { for (int i = 0; i < current_element; ++i) { printf("%c ", dynamic[i]); } printf("\n%c\n", dynamic[current_element-1]); printf("%lu\n", sizeof(dynamic)); } return 0;}
运行结果:
a b c d d8
0 0
- 指针与动态数组
- 字符数组,指针与数组,动态数组
- 指针、动态内存、字符数组与字符指针
- C++指向指针的指针与动态数组
- 数组与指针的艺术 第十章 动态数组
- 指向数组的指针与动态二维数组
- 指针:指针与数组
- 指针与指针数组
- 动态数组(指针)
- 指针 和 动态数组
- 动态申请指针数组
- 指针---动态二维数组
- C++动态指针数组
- 动态数组指针应用
- 指针数组与数组指针
- 指针数组与数组指针
- 指针数组与数组指针
- 指针数组与数组指针
- Oracle表分区
- access2003 不能更新:当前正在被机器'xxxxx'上的用户‘xxxxxx’锁定
- mysql错误1548 Cannot load from mysql.proc的最终解决方法
- PHP运行模式cgi 、fast-cgi、cli 命令行、web模块模式
- jsp—拼音检索中文
- 指针与动态数组
- MFC,win32,linux C中SetTimer定时器用法
- Hadoop 第二课 Hadoop2.7.3集群搭建
- Notepad++设置
- 基础语法1
- 模拟浏览器自动化测试工具Selenium之一eclipse集成开发部署篇
- cocos2d luajit对Lua脚本编译加密的批处理工具
- gops2016全球运维大会亮点抢先看!
- gabor 滤波的c++实现与该类得使用简介