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,945 questions

51,887 answers

573 users

How to dynamically create and handle struct with array of strings in C

1 Answer

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

struct StringArray {
    size_t arraySize;
    size_t numberOfElements;
    char** elements;
};
typedef struct StringArray* StringArray;

StringArray StringArray_new(size_t size) {
    StringArray this = calloc(1, sizeof(struct StringArray));
    if (this) {
        this->elements = calloc(size, sizeof(size_t));
        if (this->elements)
            this->arraySize = size;
        else {
            free(this);
            this = NULL;
        }
    }
    return this;
}

void StringArray_add(StringArray this, ...) {
    char* str;
    va_list args;
    va_start(args, this);
    while (this->numberOfElements < this->arraySize && (str = va_arg(args, char*)))
        this->elements[this->numberOfElements++] = _strdup(str);
    va_end(args);
}

void StringArray_print(StringArray this) {
    for (size_t i = 0; i < this->numberOfElements; i++)
        printf("element %zu = %s\n", i, this->elements[i]);
}

void StringArray_free(StringArray this) {
    assert(this != NULL);
    if (this) {
        for (size_t i = 0; i < this->numberOfElements; i++)
            free(this->elements[i]);
        free(this->elements);
        free(this);
        this = NULL;
    }
}

int main()
{
    StringArray sa = StringArray_new(7);
    StringArray_add(sa, "c", "c++", "java", NULL);

    printf("%zu elements in array with a size of %zu\n", sa->numberOfElements, sa->arraySize);

    StringArray_print(sa);

    StringArray_free(sa);

    return 0;
}





/*
run:
 
3 elements in array with a size of 7
element 0 = c
element 1 = c++
element 2 = java
 
*/

 



answered Dec 9, 2022 by avibootz
edited Dec 9, 2022 by avibootz

Related questions

1 answer 98 views
1 answer 95 views
1 answer 163 views
2 answers 177 views
1 answer 209 views
...