memset in C: solved exercise to initialize arrays and buffers

memset in C: solved exercise

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

Problem statement

Create a program that:

  • initializes a text buffer with '*',
  • initializes an integer array to 0,
  • prints both outputs to verify the final state.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#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;
}

Expected output

1
2
Buffer: **********
Nums: 0 0 0 0 0

Common mistakes

  • Using memset to set non-zero values in int arrays.
  • Passing element count instead of byte count.
  • Forgetting the \0 terminator for text buffers.

Practical use

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

Guided practice and full book

If you want a complete path with progressive difficulty:

FAQ

Does memset work for every data type?

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

Why is sizeof(array) important with memset?

Because memset expects bytes, not element count.

Is memset faster than a loop?

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