Summer training at Goeduhub Technologies-Jaipur

Online Instructor-Led Live Training Courses/Workshops details || Claim for online workshop's certificate

0 like 0 dislike
23 views
in Tutorial & Interview questions by Goeduhub's Expert (7.3k points)

Clearing array contents (zeroing)

1 Answer

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

Related questions

0 like 0 dislike
1 answer
 Know About Popular Colleges/Universities  List of IITsList of NITs | RTU-Kota | BTU-Bikaner | Manipal University-Jaipur | JECRC University | Amity University Jaipur | BIT Mesra-Jaipur | MODY UNIVERSITY | LNMIIT-Jaipur | JK Lakshmipat | Banasthali Vidyapith | POORNIMA University
 Exams:   List of Exams After Graduation | List of Engineering Entrance Examinations (UG/PG) | JEE Main | JEE Advanced | GATE | IES | ISROList of PSUs
Placements:  List of companies | Logical Reasoning Questions | Quantitative Aptitude Questions | General English Questions | Technical-MCQ and Interview Questions
 Download Previous Year Papers For:  GATE | IES | RAJASTHAN TECHNICAL UNIVERSITY (RTU-Kota)RPSC Technical Exams | ISRO
 Online Free Training:  Artificial Intelligence(AI) & Machine Learning(ML)Python Programming | Internet of Things-IoT | OpenCV (Open Source Computer Vision Library) | LINUX | Big Data : Hadoop | 
 Goeduhub
About Us | Contact Us   Social::   |  | 
...