C documentation V1 Help

Utility Functions in C

Overview

Utility functions in C serve various purposes, providing functionalities beyond basic arithmetic and mathematical operations. These functions, often included in standard libraries, offer solutions for common programming tasks. Here's an overview of some commonly used utility functions in C:

1. Random Number Generation

a. rand (Generate Random Number):

  • Generates a pseudo-random integer.

    #include <stdlib.h> int rand(void);

b. srand (Seed for Random Number Generator):

  • Seeds the random number generator.

    #include <stdlib.h> void srand(unsigned int seed);

2. Memory Allocation and Deallocation

a. malloc (Memory Allocation):

  • Allocates a block of memory of specified size.

    #include <stdlib.h> void *malloc(size_t size);

b. calloc (Contiguous Memory Allocation):

  • Allocates a block of memory for an array.

    #include <stdlib.h> void *calloc(size_t num, size_t size);

c. realloc (Reallocate Memory):

  • Changes the size of a previously allocated block of memory.

    #include <stdlib.h> void *realloc(void *ptr, size_t size);

d. free (Free Allocated Memory):

  • Deallocates the memory block.

    #include <stdlib.h> void free(void *ptr);

3. System Utilities

a. system (Execute System Command):

  • Executes a shell command.

    #include <stdlib.h> int system(const char *command);

4. Date and Time Functions

a. time (Get Current Time):

  • Returns the current calendar time.

    #include <time.h> time_t time(time_t *timer);

b. ctime (Convert Time to String):

  • Converts the time to a string representation.

    #include <time.h> char *ctime(const time_t *timer);

5. Conversion Functions

a. atoi (String to Integer):

  • Converts a string to an integer.

    #include <stdlib.h> int atoi(const char *str);

b. atof (String to Double):

  • Converts a string to a double.

    #include <stdlib.h> double atof(const char *str);

c. itoa (Integer to String):

  • Converts an integer to a string.

    #include <stdlib.h> char *itoa(int value, char *str, int base);

These utility functions contribute to the versatility of C programming, allowing developers to address diverse requirements in their applications.

If you have specific questions or if there are additional topics you'd like to explore, feel free to ask!

Last modified: 25 February 2024