Reputation: 3819
I'm a bit confused on how to accomplish this task.
Let's say I define an array with size 5
int array[] = {1, 2, 3, 4, 5};
Then I remove an element in the first index, i.e. 1
How do I shift the elements to the left, and shrink the size by 1 to accomplish this?
int array[] = {2, 3, 4, 5};
Now the array size should be 4, i.e. I dont want the last index 4 to still contain 5, I would like the last index to be deleted so that the size of the array is 4
I have this code and went in reverse order but I dont think it's right:
for (int i = sizeof(array) - 1; i >= 0; i--)
{
array[i-1] = array[i];
}
But then I'm not sure where to go next.
I read something on SO about malloc, but even after seeing the code, I'm not sure how to use it.
Upvotes: 0
Views: 758
Reputation:
You can use realloc() function refer http://en.wikipedia.org/wiki/C_dynamic_memory_allocation
Upvotes: 0
Reputation: 7246
C does not allow you to do this at all because the size of the array is not decided at runtime.
The memory for an array is allocated either statically or automatically, depending on some specifics of your program. Statically and automatically allocated memory is not "affected" by runtime variables or changes, which you can see in C's inability to do something like: int breaks[some_runtime_variable]
.
If you'd like to read more about memory allocation in C, and some ways of how to solve this problem using dynamic memory allocation, see my answer on Quora here: http://qr.ae/htfYE
To be a bit more specific to this question, here's a toy implementation of a stack in C.
As you can see from the implementations of push and pop, the stack explicitly keeps track of its current size as a separate field of the struct, which allows constant time LIFO pushes and pops.
The stack doesn't technically "shrink" when you pop from it, but if you treat the stack implementation like a black box it may as well shrink when you pop and grow when you push.
Upvotes: 2