How to quickly zero out an array?

Viewed 90038

I am currently doing it in a for loop, and I know in C there is the ZeroMemory API, however that doesn't seem to be available in C#. Nor does the somewhat equivalent Array.fill from Java exist either. I am just wondering if there is an easier/faster way?

7 Answers

I believe this is what you're looking for I wrote this in visual basic however I'm sure you can convert it.

Imports System.Runtime.InteropServices

Module Module1

    'import Kernel32 so we can use the ZeroMemory Windows API function
    <DllImport("kernel32.dll")>
    Public Sub ZeroMemory(ByVal addr As IntPtr, ByVal size As IntPtr)

    End Sub

    Private Sub ZeroArray(array As ArrayList)
        'Iterate from 0 to the lenght of the array zeroing each item at that index
        For i As Integer = 0 To array.Count - 1
            'Pin the array item in memory
            Dim gch As GCHandle = GCHandle.Alloc((array(i)), GCHandleType.Pinned)
            'Get the memory address of the object pinned
            Dim arrayAddress As IntPtr = gch.AddrOfPinnedObject()
            'Get size of the array
            Dim arraySize As IntPtr = CType(array.Count, IntPtr)
            'Zero memory at the current index address in memory
            ZeroMemory(arrayAddress, arraySize)
            gch.Free()
        Next

    End Sub


    Sub Main()
        'Initialize ArrayList with items
        Dim strArray As New ArrayList From {
            "example one",
            "example two",
            "example three"
        }

        'Pass array as parameter to a function which will iterate through the arraylist zeroing each item in memory
        ZeroArray(strArray)

        Console.ReadLine()
    End Sub

End Module
Related