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.

39,939 questions

51,876 answers

573 users

How to implement C++ vector and push_back() function in C

1 Answer

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

typedef struct  {
    char** data;
    int size;
    int capacity;
} Vector;

void vector_init(Vector* vec) {
    vec->data = NULL;
    vec->size = 0;
    vec->capacity = 0;
}

void vector_push_back(Vector* vec, const char* value) {
    if (vec->size >= vec->capacity) {
        vec->capacity = (vec->capacity == 0) ? 1 : vec->capacity * 2;
        vec->data = (char**)realloc(vec->data, vec->capacity * sizeof(char*));
    }
    vec->data[vec->size] = (char*)malloc((strlen(value) + 1) * sizeof(char));
    
    strcpy(vec->data[vec->size], value);
    
    vec->size++;
}

int main() {
    Vector vec;
    
    vector_init(&vec);
    
    vector_push_back(&vec, "c++");
    vector_push_back(&vec, "c");
    vector_push_back(&vec, "c#");
    vector_push_back(&vec, "java");
    vector_push_back(&vec, "python");
    vector_push_back(&vec, "php");
    vector_push_back(&vec, "rust");

    for (int i = 0; i < vec.size; i++) {
        printf("%s\n", vec.data[i]);
    }

    for (int i = 0; i < vec.size; i++) {
        free(vec.data[i]);
    }
    
    free(vec.data);

    return 0;
}




/*
run:

c++
c
c#
java
python
php
rust

*/

 



answered Sep 6, 2023 by avibootz

Related questions

2 answers 228 views
1 answer 116 views
1 answer 121 views
1 answer 57 views
57 views asked Jun 10, 2025 by avibootz
1 answer 112 views
1 answer 109 views
...