Thread: how to use memset for int?

  1. #1
    Banned
    Join Date
    Nov 2007
    Posts
    678

    how to use memset for int?

    Code:
    int arr[512];
    int val = 5;
    
    /*
    how i use memset() to set all the elements of arr[] to val?
     */

  2. #2
    Registered User
    Join Date
    Apr 2007
    Location
    Sydney, Australia
    Posts
    217
    I dont think you can with memset. You can set each BYTE of that block of memory to 5 but not each element (which is made up of 4 bytes)

    Code:
    for(unsigned int i = 0; i < sizeof(arr) / sizeof(*arr); ++i)
      arr[i] = val;

  3. #3
    Banned
    Join Date
    Nov 2007
    Posts
    678
    yeah! i had to do the obvious:
    Code:
    void fill_grid(int* grid, int nr, int nc, int val)
    {
    	int i;
    	for (i=0; i<(nr*nc); i++)
    	{
    		grid[i] = val;
    	}
    }
    but since assembly has the instructions for byte,word and dword:
    stodb, stosw, stosd
    and memset works very fast, i thougt may be there is something to set ints as well!

  4. #4
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    but since assembly has the instructions for byte,word and dword:
    stodb, stosw, stosd
    and memset works very fast, i thougt may be there is something to set ints as well
    leave it to compiler's optimizer
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  5. #5
    Registered User
    Join Date
    Apr 2007
    Location
    Sydney, Australia
    Posts
    217
    Quote Originally Posted by manav View Post
    yeah! i had to do the obvious:
    Code:
    void fill_grid(int* grid, int nr, int nc, int val)
    {
    	int i;
    	for (i=0; i<(nr*nc); i++)
    	{
    		grid[i] = val;
    	}
    }
    but since assembly has the instructions for byte,word and dword:
    stodb, stosw, stosd
    and memset works very fast, i thougt may be there is something to set ints as well!
    Code:
        int* maxPtr = arr + 512;
        int* ptr = arr;
        while(ptr < maxPtr)
            *ptr++ = val;
    Thats probably the fastest way.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. info on memset and recv
    By lolguy in forum Networking/Device Communication
    Replies: 15
    Last Post: 11-12-2009, 05:48 AM
  2. problem using 'memset'
    By ezwise in forum C Programming
    Replies: 2
    Last Post: 03-17-2005, 11:27 AM
  3. Simple Question on Correct Usage of memset
    By deadpoet in forum C++ Programming
    Replies: 2
    Last Post: 03-16-2004, 08:58 AM
  4. memset has conflicting declaration
    By mangoMan in forum C++ Programming
    Replies: 2
    Last Post: 03-02-2004, 10:08 AM
  5. memset() or ZeroMemory()
    By jdinger in forum C++ Programming
    Replies: 2
    Last Post: 05-10-2002, 09:38 AM