Winter Bootcamp in ML and IoT in Jaipur
 Course content (For Bootcamp & Winter Training):- Machine Learning (ML) || Internet of Things (IoT) || Register for winter bootcamp
0 like 0 dislike
in Tutorial & Interview questions by (3.3k points)

Clearing array contents (zeroing)

1 Answer

0 like 0 dislike
by (3.3k points)
 
Best answer
Sometimes it's necessary to set an array to zero, after the initialization has been done.

#include <stdlib.h>         /* for EXIT_SUCCESS */

#define ARRLEN (10)

int main(void)

{  

int array[ARRLEN];          /* Allocated but not initialised, as not defined static or global. */

  size_t i;  

for(i = 0; i < ARRLEN; ++i)  

{    

array[i] = 0;  

}

return EXIT_SUCCESS;

}

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.

memset(array, 0, ARRLEN * sizeof (int));     /* Use size explicitly provided type (int here). */

or

memset(array, 0, ARRLEN * sizeof *array);    /* Use size of type the pointer is pointing to. */

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:

 memset(array, 0, sizeof array);      /* Use size of the array itself. */

Winter 10 Days boot-camp classes(7 HRS Daily) will start from 5, 20 & 27 December 2019 in:
1) Internet of things(IoT) Using RASPBERRY-PI
2) Machine Learning (ML)

70% OFF| Fee-INR 3,000/-

Limited seats!! Hurry up!!

[[ CALL - 07976731765 ]]

Some Study Resources are compiled from original Stack Overflow Documentation, the content is developed by the different experts at Stack Overflow. Study resources are released under Creative Commons BY-SA. Images may be copyright of their respective owners. This website is for self-learning and not affiliated with Stack Overflow. All trademarks and registered trademarks are the property of their respective company owners. Please send feedback and corrections to chandwaglobal@gmail.com.

Goeduhub Important Lists Our Youtube Channels (For free E-learning)
About Us List of IITs Goeduhub Technologies
Contact Us List of NITs AI and Big Data-HADOOP E-Learning Series
  List of PSUs Smart Learning PLC-SCADA, IoT and Raspberry-PI
  List of Exams After Graduation  
...