Finance[US] Career Guide Free Tutorials Go to Your University Placement Preparation 
0 like 0 dislike
331 views
in Tutorial & Interview questions by Goeduhub's Expert (9.3k points)

 Allocate and zero-initialize an array with user defined size

1 Answer

0 like 0 dislike
by Goeduhub's Expert (9.3k 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().

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

...