Summer training at Goeduhub Technologies-Jaipur
Register for Free Certified Workshop on AI & Machine Learning:: 02-02-2020 ||  Career options for aspiring CS/ITECEEE or EIC or EEE Engineers
0 like 0 dislike
17 views
in Tutorial & Interview questions by (6.7k points)

 Allocate and zero-initialize an array with user defined size

1 Answer

0 like 0 dislike
by (6.7k points)
 
Best answer
#include <stdio.h>

#include <stdlib.h>

int main (void)

{  

int * pdata;  

size_t n;

printf ("Enter the size of the array: ");  

fflush(stdout);                  /* Make sure the prompt gets printed to buffered stdout. */

if (1 != scanf("%zu", &n))              /* If zu is not supported (Windows?) use lu. */  

{    

fprintf("scanf() did not read a in proper value.\n");    

exit(EXIT_FAILURE);  

}

pdata = calloc(n, sizeof *pdata);  

if (NULL == pdata)  

{    

perror("calloc() failed");                              /* Print error. */    

exit(EXIT_FAILURE);  

}

free(pdata);                    /* Clean up. */

return EXIT_SUCCESS;

}

This program tries to scan in an unsigned integer value from standard input, allocate a block of memory for an array of n elements of type int by calling the calloc() function. The memory is initialized to all zeros by the latter.

In case of success the memory is releases by the call to free().
 Go to your Branch CSE or IT | ECE | EE, EIC or EEEMECE
 Know About Popular Colleges/Universities  List of IITsList of NITs | RTU-KOTA | 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 | Python Programming | Internet of Things-IoT | OpenCV (Open Source Computer Vision Library) | LINUX | Big Data : Hadoop | 
 Goeduhub
About Us | Contact Us   Social::   |  | 
...