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.2k points)

 Allocate and zero-initialize an array with user defined size

1 Answer

0 like 0 dislike
by (3.2k 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().

Winter 10 Days bootcamp classes(7 HRS Daily) will start from 5 & 20 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.

...