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 114 views
1 answer 110 views
1 answer 179 views
2 answers 219 views
1 answer 226 views
...