C Programming Language

Array Dinamis di C

Aldimhr
18-04-2026
4 min read

Array Dinamis di C

Bahasa pemrograman C menyediakan tipe data array secara default. Sayangnya tidak mendukung array dinamis.

Secara default kita tidak bisa menentukan panjang array setelah inisialisasi, contohnya kita akan inisialisasi array dengan variable lain, lalu kita akan melakukan increment untuk variabel yang digunakan.

#include <stdio.h>

int main(void){
  int x = 10;
  int arr[x];

  for(int i = 0; i < 100; i++, x++){
    arr[i] = i;
    printf("value index-%d: %d\n", i, arr[i]);
  }
  return 0;
}

Kode diatas akan terjadi error [1] 22750 segmentation fault (core dumped) karena kita tidak bisa melakukan resize array dengan cara ini.

Dynamic Array

Kita bisa membuat array dinamis menggunakan pointer dan struct.

Pertama kita buat struct untuk menampung value yang akan disimpan. Didalamnya terdapat tiga variabel:

  1. items → untuk menyimpan value
  2. used → untuk menyimpan total items yang sudah disimpan (index)
  3. capacity → kapasitas memory yang digunakan untuk menyimpan value array
struct Numbers {
  int *items;
  size_t used;
  size_t capacity;
};

Kedua kita bikin function untuk menambahkan member array, stepnya:

  1. Pertama, perlu cek apakah capacity sama dengan 0? jika iya ini berarti pertama kali inisialisasi
  2. Kedua, perlu cek apakah used lebih besar atau sama dengan capacity? jika iya, kita perlu memperbesar capacity untuk menampung member array
  3. Ketiga, kita akan melakukan reallocation memory untuk items
  4. Keempat, kita akan tambahkan valuenya ke items
  5. Kelima, increment used
// kita melakukan perubahan in-place (langsung ke array aslinya)
void add(struct Numbers *x, int value){
  if(x->used >= x->capacity){
    if(x->capacity == 0) x->capacity = 256;
    else x->capacity *= 2;

    x->items = realloc(x->items, sizeof(x->items) * x->capacity);
  }

  x->items[x->used++] = value;
}

Disini kita sudah membuat struct untuk menampung array, juga function add yang akan digunakan ketika akan menambahkan value ke array. Cara menggunakannya

int main(void){
  struct Numbers arr = {0}; // set semua value menjadi 0

  for(int i = 0; i < 10; i++){
    add(&arr, i); // menambahkan data ke arr
  }
}

Free Memory

Meskipun kode diatas berhasil menambahkan value ke array, kita wajib melakukan free memory, jika kita lihat hasil dari valgrind, kita akan melihat error berikut

❯ valgrind --leak-check=full ./output
==28292== Memcheck, a memory error detector
==28292== Copyright (C) 2002-2024, and GNU GPL'd, by Julian Seward et al.
==28292== Using Valgrind-3.25.1 and LibVEX; rerun with -h for copyright info
==28292== Command: ./output
==28292== 
==28292== HEAP SUMMARY:
==28292==     in use at exit: 2,048 bytes in 1 blocks
==28292==   total heap usage: 2 allocs, 1 frees, 3,072 bytes allocated
==28292== 
==28292== 2,048 bytes in 1 blocks are definitely lost in loss record 1 of 1
==28292==    at 0x4852E4F: realloc (vg_replace_malloc.c:1801)
==28292==    by 0x4001221: add (in /path/output)
==28292==    by 0x4001291: main (in /path/output)
==28292== 
==28292== LEAK SUMMARY:
==28292==    definitely lost: 2,048 bytes in 1 blocks
==28292==    indirectly lost: 0 bytes in 0 blocks
==28292==      possibly lost: 0 bytes in 0 blocks
==28292==    still reachable: 0 bytes in 0 blocks
==28292==         suppressed: 0 bytes in 0 blocks
==28292== 
==28292== For lists of detected and suppressed errors, rerun with: -s
==28292== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

Terdapat 1 error, yang masih melakukan alokasi memori setelah program exit.

Karena arr.items menggunakan realloc kita harus melakukan free

free(arr.items);

Setelah itu, output dari valgrind sudah tidak ada error

❯ valgrind --leak-check=full ./output
==29735== Memcheck, a memory error detector
==29735== Copyright (C) 2002-2024, and GNU GPL'd, by Julian Seward et al.
==29735== Using Valgrind-3.25.1 and LibVEX; rerun with -h for copyright info
==29735== Command: ./output
==29735== 
==29735== HEAP SUMMARY:
==29735==     in use at exit: 0 bytes in 0 blocks
==29735==   total heap usage: 2 allocs, 2 frees, 3,072 bytes allocated
==29735== 
==29735== All heap blocks were freed -- no leaks are possible
==29735== 
==29735== For lists of detected and suppressed errors, rerun with: -s
==29735== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Full Code

#include <stdio.h>
#include <stdlib.h>

struct Numbers {
  int *items;
  size_t used;
  size_t capacity;
};

void printArr(struct Numbers arr){
  for(int i = 0; i < arr.used; i++){
    printf("value arr index-%d: %d\n", i, arr.items[i]);
  }
}

void add(struct Numbers *x, int value){
  if(x->used >= x->capacity){
    if(x->capacity == 0) x->capacity = 256;
    else x->capacity *= 2;

    x->items = realloc(x->items, sizeof(x->items) * x->capacity);
  }

  x->items[x->used++] = value;
}

int main(void){
  struct Numbers arr = {0};

  for(int i = 0; i < 10; i++){
    add(&arr, i);
  }

  printArr(arr);

  free(arr.items);
}

Typedef

#include <stdio.h>
#include <stdlib.h>

typedef struct {
  int *items;
  size_t used;
  size_t capacity;
} Numbers;

void printArr(Numbers arr){
  for(int i = 0; i < arr.used; i++){
    printf("value arr index-%d: %d\n", i, arr.items[i]);
  }
}

void add(Numbers *x, int value){
  if(x->used >= x->capacity){
    if(x->capacity == 0) x->capacity = 256;
    else x->capacity *= 2;

    x->items = realloc(x->items, sizeof(x->items) * x->capacity);
  }

  x->items[x->used++] = value;
}

int main(void){
  Numbers arr = {0};

  for(int i = 0; i < 10; i++){
    add(&arr, i);
  }

  printArr(arr);

  free(arr.items);
}
Tags
  • C Programming Language
  • Memory Address
  • Array
View All Posts