Gadgets 4 Students Career Guide Free Tutorials  Go to Your University  Placement Preparation 
0 like 0 dislike
274 views
in Tutorial & Interview questions by Goeduhub's Expert (9.3k points)

Clearing array contents (zeroing)

1 Answer

0 like 0 dislike
by Goeduhub's Expert (9.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. */

Learn & Improve In-Demand Data Skills Online in this Summer With  These High Quality Courses[Recommended by GOEDUHUB]:-

Best Data Science Online Courses[Lists] on:-

Claim your 10 Days FREE Trial for Pluralsight.

Best Data Science Courses on Datacamp
Best Data Science Courses on Coursera
Best Data Science Courses on Udemy
Best Data Science Courses on Pluralsight
Best Data Science Courses & Microdegrees on Udacity
Best Artificial Intelligence[AI] Courses on Coursera
Best Machine Learning[ML] Courses on Coursera
Best Python Programming Courses on Coursera
Best Artificial Intelligence[AI] Courses on Udemy
Best Python Programming Courses on Udemy

 Important Lists:

Important Lists, Exams & Cutoffs Exams after Graduation PSUs

 Goeduhub:

About Us | Contact Us || Terms & Conditions | Privacy Policy ||  Youtube Channel || Telegram Channel © goeduhub.com Social::   |  | 

 

Free Online Directory

...