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
#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
Buffer: **********
Nums: 0 0 0 0 0Common mistakes
- Using
memsetto set non-zero values inintarrays. - Passing element count instead of byte count.
- Forgetting the
\0terminator for text buffers.
Practical use
memset is used to reset structs, clear buffers, and prepare memory before processing.
Recommended next exercise
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.