In C, strnset() fills the first n characters of a writable C-string with one byte and leaves the rest alone. The terminator stays in place when n stays inside the string. It is an extension, not ISO C.
You pass the string, the fill byte, and the count. All three are required. Prefer a portable loop when you need standard C.
Syntax
Pass a writable string, the fill character, and the count.
C
strnset(word, '*', 3);
Call
What it does
strnset(word, '*', 3)
Replaces the first 3 characters with '*'.
Not ISO C. Never pass a string literal. On Microsoft compilers the name is often _strnset.
Library declarations
C
char *strnset(char *str, int c, size_t n);
char *_strnset(char *str, int c, size_t n);
Parameters
Parameter
Description
str
Required. A writable C-string. Do not pass a string literal.
c
Required. The fill byte, often a character in single quotes.
n
Required. How many characters to overwrite.
Return Value
Return Value
Description
str pointer
The same pointer you passed in.
C Examples
Example 1 — Portable Prefix Fill
ISO C approach: overwrite up to n characters, stop at '\0'.
C
#include <stdio.h>
void str_nset(char *s, char c, int n) {
int i;
for (i = 0; i < n && s[i] != '\0'; i++) {
s[i] = c;
}
}
int main(void) {
char s[] = "Hello";
str_nset(s, '*', 3);
printf("%s\n", s);
return 0;
}
Output
***lo
How It Works
Writable array.char s[] can be modified.
Loop with two stops. End after n writes or at '\0'.
Replace three chars.H e l become * * *.
Rest unchanged.lo and the terminator remain.
Example 2 — Using strnset (Where Available)
On MSVC and some older compilers, call strnset / _strnset directly.