Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,023 questions

51,974 answers

573 users

How to resize array in C

1 Answer

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

int* allocate_array(int size) {
    int *arr = (int *) malloc(size * sizeof(int));
    if (arr == NULL) {
        printf("malloc error\n");
        exit(1);
    }
    
    return arr;
}

int* resize_array(int *arr, int old_size, int new_size) {
    int *tmp = (int *) realloc(arr, new_size * sizeof(int));
    if (tmp == NULL) {
        free(arr);
        printf("realloc error\n");
        exit(1);
    }
    // Optionally initialize new elements to 0
    for (int i = old_size; i < new_size; i++) {
        tmp[i] = 0;
    }
        
    return tmp;
}

void print_array(int *arr, int size) {
    for (int i = 0; i < size; i++) {
        printf("%i\n", arr[i]);
    }
}

int main(void) {
    int *arr = allocate_array(3);

    arr[0] = 10;
    arr[1] = 20;
    arr[2] = 30;

    print_array(arr, 3);

    arr = resize_array(arr, 3, 5);

    printf("\nafter realloc\n");
    print_array(arr, 5);

    arr[3] = 40;
    arr[4] = 50;

    printf("\nafter realloc & set new data\n");
    print_array(arr, 5);

    free(arr);
    
    return 0;
}



/*
run

10
20
30

after realloc
10
20
30
0
0

after realloc & set new data
10
20
30
40
50

*/


answered Mar 5, 2015 by avibootz
edited Oct 14, 2025 by avibootz

Related questions

1 answer 61 views
1 answer 178 views
3 answers 68 views
2 answers 86 views
2 answers 61 views
...