Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending values to c array

Tags:

arrays

c

This is a very simple question, but I don't know how to do this.

For example, I have an array called Arraycontaining the values[1,2,3,4,5,6], and I want to add a seventh value, 7, to the array so it contains[1,2,3,4,5,6,7].

Is there a function to do that? Do I need to include any extra header files? Any help would be appreciated.

like image 903
Pyraminx Avatar asked Feb 05 '26 07:02

Pyraminx


2 Answers

If it is a plain array declared as such:

int Array[] = {1,2,3,4,5,6};

Then you wouldn't be able to add more values to it. If there's some space provided in advance then you may add more values:

int Array[7] = {1,2,3,4,5,6};
Array[6] = 7;

If you used c++, I would recommend using std::vector, but it does not exist in C.

like image 61
Juster Avatar answered Feb 06 '26 20:02

Juster


Nope. No information is stored about the size of, or the number of occupied elements, of an array in C. You could devise a struct and a procedure that did this, but the language does not do it for you.

struct cvector
{
    int *content;
    int occupied;
    int size;
};

void cvector_init(struct cvector *v)
{
    v->content = malloc(sizeof *(v->content) * 16;
    v->size = 16;
    v->occupied = 0;
}

void cvector_kill(struct cvector *v)
{
    free(v->content);
}

// returns true if an error occurred, as is the style with linux syscalls.
int cvector_append(struct cvector *v, int value)
{
    if (v->occupied == v->size)
    {
        int new_size = v->size * 1.75;
        int *new_content = realloc(v->content, new_size);
        if (new_content == NULL) return 1;
        v->content = new_content;
        v->size = new_size;
    }
    v->content[v->occupied++] = value;
    return 0;
}
like image 41
Wug Avatar answered Feb 06 '26 22:02

Wug