How to use calloc and snprintf in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h> 

int main(void)
{
    // void *calloc(size_t nmemb, size_t size);
    // nmemb: The number of elements in the array.
    // size: The size of each element in bytes.
    char* buff = calloc(1, 15); 
    if (!buff) { fprintf(stderr, "Memory Failure.\n"); exit(EXIT_FAILURE); }

    int a = 714;
    int b = 9012;
    char c[4] = "ABC";

    // snprintf(str, size, format, ...);
    // str: It is a pointer to the buffer.
    // size: It is the maximum number of bytes that will be written to the buffer.
    // format: %c%d... like in printf.
    // Return Value - The number of characters that have been written on the buffer
    int result = snprintf(buff, 14, "%03d-%04d-%s", a, b, c);

    printf("result is: %d - buff is: %s\n", result, buff);

    free(buff); // release resources no longer needed

    return 0;
}



/*
run:

result is: 12 - buff is: 714-9012-ABC

*/

 



answered Jun 2, 2025 by avibootz

Related questions

1 answer 110 views
2 answers 108 views
108 views asked Dec 19, 2021 by avibootz
2 answers 215 views
215 views asked Aug 4, 2017 by avibootz
...