1. 程式人生 > >指標與動態陣列

指標與動態陣列

C語言中如何實現動態陣列:

  1. 使用malloc()庫函式(記憶體分配)來得到一個指向一大塊記憶體的指標;
  2. 像引用陣列一樣引用這塊記憶體

如果需要使陣列有動態增長的能力,那就修改記憶體的總容量,直接在執行時在堆上分配陣列的記憶體。這就用到庫函式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 
d
8