Перейти к содержимому

Как очистить ячейку массива c

  • автор:

How to Delete Elements from an Array in C#

How to Delete Elements from an Array in C#

In this article, we will explore several different ways to delete elements from an array in C# based on their value and compare their performance to help you choose the best option for your specific use case.

Arrays in .NET

Arrays are a fundamental data structure in .NET, allowing developers to easily store and manipulate collections of data. However, deleting elements from an array can be a challenging task, as the size of the array is fixed once we initialize it.

To overcome this, we will demonstrate various techniques to remove elements from an array, each with its advantages and disadvantages.

Methods to Delete Array Elements

Array type does not have a built-in method for this task and we often resort to alternative techniques such as converting the Array to a List or utilizing LINQ to remove specific elements from the Array. These methods provide greater flexibility and ease when it comes to removing unwanted elements from the Array.

The solutions are built with integer arrays for demonstration purposes, but we can apply them to any data type.

We’ll start by setting up a simple example to test against our methods:

Here, we construct an array of integers and we assign to the elementToDelete variable the value we want to remove from our collection.

Use Array.Copy() To Delete an Element From an Array

First, we will manually remove it with the ArrayCopy() extension method:

The DeleteWithArrayCopy() method takes as arguments an inputArray integer array and an elementToRemove integer.

First, we find the index of the elementToRemove integer in the inputArray array using the built-in Array.IndexOf() method.

If the elementToRemove is not found in the inputArray , we simply return the inputArray .

Otherwise, we create a new integer array tempArray with length that is one less than the inputArray array’s length. Then, we copy all elements from the original array except the elementToRemove into it using the Copy() method. Finally, we return the tempArray array.

So we end up with:

Modified Array: 4,5,3,5,7

Otherwise, we construct two new ArraySegment objects. We create an ArraySegment object from the beginning of the inputArray to the index of the element to remove. Then, we create a second one from the right next position of the calculated index to the end of the inputArray .

Finally, we store the concatenation of these two segments into the tempArray using the Concat() method and convert the resulting IEnumerable to an array using the ToArray() method.

Use a For Loop to Remove an Element

Our next solution makes use of a loop and a temporary array:

If the element does not exist in the array, we return the original inputArray . Differently, we create a new integer tempArray array of size equal to the size of inputArray decreased by one.

Finally, we return the tempArray which does not include the first instance of the specified element.

Also, we can refactor this method to use the Array . Resize() method:

Here, in the for loop, we shift every element after the indexToRemove one position to the left.

Then, we decrease the array size by one, with the use of the Array.Resize() method. To achieve this, we pass the array as a reference and the new length.

However, we need to be cautious when we use arrays by reference. One type of issue that might arise is thread related. For example, if multiple threads access the same array that is passed by reference, it can lead to race conditions and other synchronization problems.

Remove an Element with the Use of Buffer.BlockCopy()

Also, we can use the BlockCopy() extension method of the Buffer class for removing an element:

First, we check if the element to remove is actually in the inputArray by using the Array.IndexOf() method. If the element does not exist, we return the original inputArray . Otherwise, we create the tempArray , with a length of one less than the inputArray .

When we use the Buffer.BlockCopy() method to copy integers, we typically multiply the second, fourth, and fifth parameters by 4 to account for the fact that each integer in C# has a size of 4 bytes.

The first call to the Buffer.BlockCopy() method copies the elements before the index of the element to remove. The second call copies the elements after that index.

Finally, we return the tempArray . We use this method to efficiently remove an element from an array without having to manually shift elements around.

Delete Multiple Elements With the Where() Extension

Next, we can use the Where() extension method of LINQ:

Here, we use the Where() extension method to filter out all elements from the input array that are not equal to the elementToRemove variable.

Subsequently, we convert the resulting sequence of elements back to an integer array using the ToArray() method and we return it.

We achieve the same result as the previous methods, but with a more concise syntax, using LINQ.

FindAll() Extension to Delete Array Elements

Another similar approach is with the FindAll() extension method:

Here, we use the FindAll() method of the Array class to return all elements from the input array that are not equal to the elementToRemove value.

Use the RemoveAll() Extension

We can achieve the same results for deleting elements from an array by using the RemoveAll() method:

First, we create a new List<int>() object from the inputArray array argument.

Then we use the RemoveAll() method of the List<T> class to remove all elements in the list that are equal to the elementToRemove .

Finally, we return the list back to an integer array using again the ToArray() method.

Use a For Loop and a List() to Remove Multiple Elements

Here, we can make use of a for loop and a List collection to remove elements:

After we check if the element exists in our input source array, we create a new List<int> object with an initial capacity equal to the length of the inputArray .

Finally, we return the new integer array using the List<T>.ToArray() method. The resulting array contains all the elements of the original inputArray except for the elementToRemove .

Use ArrayPool To Remove Multiple Elements

We can take advantage of using the array from the ArrayPool to skip a buffer allocation in comparison with the List option:

We can even improve this code by installing the CommunityToolkit.HighPerformance NuGet package, which enables cleaner work with ArrayPool.

A big thanks to Jeff S. who suggested this solution in the comment section.

What’s the Fastest Way to Delete an Element From an Array?

We will evaluate these methods to find the most efficient one in terms of speed, with the benchmark class. Let’s create a method to use in our benchmark:

Here, we return a random integer array of length 1000 using the .NET Random class, with each element of the array being a random number between 1 and 10.

We benchmark our suggested solutions by removing an element from the generated array accordingly.

This approach avoids looping through the input array and copying elements one by one, which can be slow. It uses a built-in method that can copy large blocks of memory efficiently.

Also, if we check the reference code of the Buffer.BlockCopy() method, we are advised to use the Array.Copy() method when we manipulate traditional array element indices.

So, when we want to remove only one instance of an element from an array, the most efficient way is to use the DeleteWithArrayCopy() method.

Now, let’s benchmark the solutions that remove every instance from the given array:

When it comes to deleting multiple elements, the DeleteWithPooledArray() method seems to be the winner.

The methods that use LINQ such as DeleteWithRemoveAll() and DeleteWithWhere() include lambda expressions and delegates to define the condition for removing elements, which adds some overhead compared to the other methods.

C program to delete an element from an array

This tutorial will show you how to delete an element from an array in C.

Problem description #

We have an array of integers and we want to delete an element from it.

Examples #

Problem Solution #

  1. Create an array of integers.
  2. Ask the user to enter the index of the element to be deleted.
  3. Delete the element from the array.
  4. Print the array.

Delete element by index #

In this approach, we will use a loop to iterate through the array and delete the element from the array.

Approach #

  1. Create an array of integers.
  2. Ask the user to enter the index of the element to be deleted.
  3. Loop through the array and delete the element from the array.
  4. Print the array.

Program/Source code #

Explanation #

The program will ask the user to enter the size of the array and then the elements of the array. The program will then ask the user to enter the index of the element to be deleted. The program will then loop through the array and delete the element from the array. The program will then print the array.

Space Complexity #

The space complexity of this program is O(1).

Time Complexity #

The time complexity of this program is O(n).

Output #

Delete element by value #

In this approach, we will use a loop to iterate through the array and delete the element from the array.

Approach #

  1. Create an array of integers.
  2. Ask the user to enter the value of the element to be deleted.
  3. Loop through the array and delete the element from the array.
  4. Print the array.

Program/Source code #

Explanation #

The program will ask the user to enter the size of the array and then the elements of the array. The program will then ask the user to enter the value of the element to be deleted. The program will then loop through the array and delete the element from the array. The program will then print the array.

Space Complexity #

The space complexity of this program is O(1).

Time Complexity #

The time complexity of this program is O(n).

Output #

Advanced approach #

In this approach we’ll use separate functions to delete elements by index or by value and give back the array after deleting the element.

Approach #

  1. Create an array of integers.
  2. Give the user the option to delete an element by index or by value.
  3. Delete the element from the array.
  4. Print the array.

Program/Source code #

Methods used #

  • delete_element_by_index() — This function will delete the element from the array by index.
  • delete_element_by_value() — This function will delete the element from the array by value.
  • print_array() — This function will print the array.

Explanation #

The program will ask the user to enter the size of the array and then the elements of the array. The program will then ask the user to enter the index of the element to be deleted. The program will provide a choice between deleting element by value or by index. The program will then call the function delete_element_by_index() to delete the element from the array. The program will then call the function print_array() to print the array. The program will then ask the user to enter the value of the element to be deleted. The program will then call the function delete_element_by_value() to delete the element from the array. The program will then call the function print_array() to print the array.

How do I clear an array in C?

What would I use to clear the contents of x ? I’m not able to re-initialise it, use strcpy(x, ‘/0’) or free() .

braX's user avatar

4 Answers 4

You cannot assign anything to an array, which your variable x is. So therefore anything that starts with x = is wrong. Secondly ‘hello’ is not a string, it is a multicharacter literal which is of type int , so this doesn’t make sense either. A string literal is enclosed by » while character (or multicharacter) literals are enclosed by ‘ .

So if you want to fill your buffer x with the string «hello» you use strncpy or even better strlcpy if available:

The strlcpy function is better because it always terminates the string with a nul character.

If you want to clear it you could do what the other answers suggested. I’d suggest using strncpy or strlcpy with an empty string as @codaddict suggested. That is the code that says most obviously «hey, I want to clear that string». If you want to remove the whole contents of the string from memory (for example if it contained a password or something like this) use memset as @Ken and @Tom suggested.

Also note that you never ever use functions like strcpy or strcat that don’t accept the size of the output buffer as a parameter. These are really not secure and cause nasty bugs and security vulnerabilities. Don’t even use them if you know that nothing can go wrong, just make a habit of using the secure functions.

C Language Arrays Clearing array contents (zeroing)

Sometimes it’s necessary to set an array to zero, after the initialization has been done.

An common short cut to the above loop is to use memset() from <string.h> . Passing array as shown below makes it decay to a pointer to its 1st element.

As in this example array is an array and not just a pointer to an array’s 1st element (see Array length on why this is important) a third option to 0-out the array is possible:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *