Hi everybody.

I'm new in C and would like to know how to delete last elements in the array?
lets say I have array arr = {1,2,3,4,5} and whant to delet last two elements.
is it possible to do?

Yes, it is possible.
It really depends on how you're using it.
The easiest way is just to set it to NULL.

The easiest way is just to set it to NULL.

How is that possible? If you set it to NULL, the value will still be there and it is zero.

int a[5] = {1,2,3,4,5};
        printf("%d", sizeof(a));//prints 20 as the size
        a[4] = NULL;
        printf("%d", sizeof(a));//prints 20 again

It is never possible to increase or decrease the size of a static array. Same is the case with adding/deleting elements to/from a static array.

Even if you go outside of the boundary, there is still a value.
So, if zero is valid number in your sequence, set it at -1.

You can use a MAX value and decrement that number so you don't go outside of that.
...but it's all an agreement that you make with your code.
C will let you do anything you want.

Think about what you would do to iterate through that array.
You would need to KNOW the upper bounds before moving through it.
That number is just an agreement.

If you were to pass that to a function, you would need to send the size also ... or agree on a terminator.
To reference a smaller portion, you would send a smaller size parameter.
To really deleted it and free the memory, it would need to be dynamically allocated.

but it's all an agreement that you make with your code.

Yes, exactly. That is all that you can do.

What I meant is, it is not possible to remove any element from an array. If it is the elements at the end, we can somehow reduce the length variable, so that it doesn't iterate beyond that. But what if you want to delete the elements in the middle? So in short, once memory is allocated for a static array, it cannot be altered. Only thing that you can do is to change the value contained in it. Usually what I have seen in many programs is the use of -1. But it is limited in a case where your array is supposed to hold negative values.

Hi everybody.

I'm new in C and would like to know how to delete last elements in the array?
lets say I have array arr = {1,2,3,4,5} and whant to delet last two elements.
is it possible to do?

Do you want to re dimension the array or set the last 2 items to zero?
If you want to re dimension the array, forget it. C has always allowed you to read past
the end of an array. arr[6] is a value on the stack (if memory serves) and what ever you read from it is what happens to be there. If you write to it and over write something important you crash the computer.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.