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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With