Reputation: 33
Let's say I have an array allocated in memory. How do I append directly to the end of the list? By this, I mean directly after the last entry already in the array.
My for loop (i=0;i<100;i++) is only adding elements to an array in certain cases, so it is not possible to append to the array using i.
My main question is: any way to append directly to the end of an array in C?
Thank you
Upvotes: 3
Views: 27740
Reputation: 1263
No built-in function for appending an array in C (C++ & C# is a different story). Just keep a pointer to your last inserted index in the array and move it forward until you reach the end of the array, that is a basic solution.
Upvotes: 2
Reputation: 4750
In a comment, you said that there is unused space in the array, and that the array is already the appropriate size. In that case, you just need a second variable to keep track of which element is "next". Each time you "add" a value to the array, you just copy that value to the element at the index specified by the second variable, and then you just increment the second variable by one.
int i;
int index = 0;
for (i = 0; i < 100; i++)
{
if (someCondition)
{
someArray[index++] = someValue;
}
}
By saying index++
, instead of ++index
, the value of index
is not actually incremented until after someValue
has been assigned to an element in the array.
int i;
int index = 0;
for (i = 0; i < 100; i++)
{
if (i >= 90)
{
// if index == 0, for instance, someValue will be assigned to
// someArray[0], and THEN index will be incremented to 1.
someArray[index++] = someValue;
}
}
// the first ten elements of someArray will be as follows:
//
// someArray[0] == 90
// someArray[1] == 91
// someArray[2] == 92
// someArray[3] == 93
// someArray[4] == 94
// someArray[5] == 95
// someArray[6] == 96
// someArray[7] == 97
// someArray[8] == 98
// someArray[9] == 99
Upvotes: 5