memset in C: solved exercise to initialize arrays and buffers

  2 minutes

If you searched for memset in C solved exercise, this example covers text buffers and integer array initialization.

Create a program that:

  • initializes a text buffer with '*',
  • initializes an integer array to 0,
  • prints both outputs to verify the final state.
#include <stdio.h>
#include <string.h>

int main(void) {
    char buffer[11];
    int nums[5];

    memset(buffer, '*', 10);
    buffer[10] = '\0';

    memset(nums, 0, sizeof(nums));

    printf("Buffer: %s\n", buffer);
    printf("Nums: ");
    for (int i = 0; i < 5; i++) printf("%d ", nums[i]);
    printf("\n");

    return 0;
}
Buffer: **********
Nums: 0 0 0 0 0
  • Using memset to set non-zero values in int arrays.
  • Passing element count instead of byte count.
  • Forgetting the \0 terminator for text buffers.

memset is used to reset structs, clear buffers, and prepare memory before processing.

If you want a complete path with progressive difficulty:

It writes bytes. It is ideal for zero-initialization, but not for every non-zero numeric value.

Because memset expects bytes, not element count.

Often yes, since it is usually optimized at low level.