C String strnset() Function

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
Extension / loop

What You’ll Learn

The strnset() function overwrites the first n characters of a string with a single character. It is a non-standard extension on some compilers; this tutorial also shows a portable loop you can use on every platform.

01

Fill n

Same char.

02

In place

Modifies str.

03

Returns str

Same pointer.

04

Not ISO C

Extension.

05

vs memset

Raw bytes.

06

vs strset

Whole str.

Definition and Usage

strnset stands for string n set. Given a writable C-string, it replaces up to n characters starting at index 0 with the byte (char)c. Characters after the limit or after an existing '\0' (when the string is shorter than n) are left unchanged.

Typical uses include masking the start of a password for display, overwriting a prefix before reuse, or quickly stamping a run of identical characters in a buffer you already treat as a string.

💡
Beginner Tip

On Linux and GCC, strnset is usually unavailable. The three-line loop in our examples is the portable replacement. For raw memory fills without caring about '\0', use memset from <string.h>.

📝 Syntax

Typical extension declaration:

C
char *strnset(char *str, int c, size_t n);

Portable alternative

C
void str_nset(char *s, char c, size_t n) {
    for (size_t i = 0; i < n && s[i] != '\0'; i++) {
        s[i] = c;
    }
}

Parameters

  • str — writable null-terminated string to modify.
  • c — fill value (stored as char).
  • n — maximum number of characters to overwrite.

Return Value

  • Returns str (pointer to the modified buffer).

⚡ Quick Reference

BeforeCallAfter
"Hello, World!"str_nset(s, '*', 5)"*****, World!"
"Hi"str_nset(s, 'X', 10)"XX" (stops at '\0')
"ABC"str_nset(s, '0', 2)"00C"
writable bufferrequirednot string literals
Fill n
str_nset(s, '*', 5);

Portable

Whole str
strset(s, '-')

Extension

Raw memory
memset(buf, 0, n)

No null stop

Clear array
buf[0] = '\0';

Empty C-str

Examples Gallery

Examples use the portable str_nset helper so they compile on Linux, macOS, and Windows. Behavior matches typical strnset extensions.

📚 Getting Started

Replace the first few characters of a writable char array.

Example 1 — Mask the First 5 Characters with *

Turn the start of "Hello, World!" into asterisks.

C
#include <stdio.h>

void str_nset(char *s, char c, size_t n) {
    for (size_t i = 0; i < n && s[i] != '\0'; i++) {
        s[i] = c;
    }
}

int main(void) {
    char str[] = "Hello, World!";

    str_nset(str, '*', 5);

    printf("Modified String: %s\n", str);

    return 0;
}

How It Works

Indices 0–4 become '*'. The comma, space, and rest of the string stay intact because n is 5.

Example 2 — Overwrite a Prefix with Zeros

Replace the first two digits in a code string with '0'.

C
#include <stdio.h>

void str_nset(char *s, char c, size_t n) {
    for (size_t i = 0; i < n && s[i] != '\0'; i++) {
        s[i] = c;
    }
}

int main(void) {
    char code[] = "42AB";

    str_nset(code, '0', 2);

    printf("Code: %s\n", code);

    return 0;
}

How It Works

Only the first two positions change. This pattern is useful when normalizing fixed-width numeric fields in legacy text records.

📈 Practical Patterns

Short strings, comparison with memset, and return value.

Example 3 — When n Is Larger Than the String

The loop stops at the existing null terminator.

C
#include <stdio.h>
#include <string.h>

void str_nset(char *s, char c, size_t n) {
    for (size_t i = 0; i < n && s[i] != '\0'; i++) {
        s[i] = c;
    }
}

int main(void) {
    char word[] = "Hi";

    str_nset(word, 'X', 10);

    printf("Result: [%s] (len=%zu)\n", word, strlen(word));

    return 0;
}

How It Works

Even though n is 10, only two characters exist before '\0'. Both become 'X'; the string does not grow.

Example 4 — strnset vs memset

memset writes exactly n bytes; str_nset respects the string length.

C
#include <stdio.h>
#include <string.h>

void str_nset(char *s, char c, size_t n) {
    for (size_t i = 0; i < n && s[i] != '\0'; i++) {
        s[i] = c;
    }
}

int main(void) {
    char a[] = "Test";
    char b[8] = "Test";

    str_nset(a, '#', 6);
    memset(b, '#', 6);
    b[6] = '\0';

    printf("str_nset: [%s]\n", a);
    printf("memset:   [%s]\n", b);

    return 0;
}

How It Works

str_nset changes four letters and stops at the original null. memset blindly writes six # bytes—we add b[6] = '\0' so printf stays safe. Use memset for buffers, not always for live C-strings.

Example 5 — Using the Return Value

Like other string functions, the helper can return str for chaining.

C
#include <stdio.h>

char *str_nset(char *s, char c, size_t n) {
    for (size_t i = 0; i < n && s[i] != '\0'; i++) {
        s[i] = c;
    }
    return s;
}

int main(void) {
    char label[] = "Secret-123";

    printf("%s\n", str_nset(label, '?', 6));

    return 0;
}

How It Works

Returning s mirrors the extension API. The first six characters of Secret become question marks; the dash and digits remain.

🚀 Common Use Cases

  • Display masking — hide the first characters of a token or PIN in logs.
  • Prefix reset — stamp a run of placeholder chars before reusing a buffer.
  • Legacy text files — pad or overwrite fixed-width field beginnings.
  • Teaching loops — simple in-place string mutation exercise.
  • Reading old code — recognize Borland/MSVC extension calls.

🧠 How strnset() Works

1

i = 0

Start at the first character of str.

Init
2

While i < n

Assign c to str[i]; stop if str[i] is '\0'.

Fill
3

Leave tail alone

Characters after the filled region stay as they were.

Preserve
=

char* str

Same buffer, first n positions (or up to null) updated.

📝 Notes

  • Not part of ISO C—verify availability or use the portable loop.
  • Requires a writable char array; never pass string literals.
  • Does not extend string length—cannot add characters past the existing '\0'.
  • c is an int but only the low byte is stored (like memset).
  • Pair conceptually with strset() (fill entire string) and memset() (raw memory).

⚡ Optimization

Filling a small prefix is O(n) and trivial. For large buffers where you do not need null-aware behavior, memset is often faster because libraries optimize it heavily. For clearing an entire C-string to empty, set buf[0] = '\0' instead of filling every byte.

Conclusion

strnset() overwrites up to n characters of a string with one byte where the extension exists. Learn the portable loop for every platform, and choose memset when you are filling raw memory instead of a live C-string.

Next, learn strpbrk() to search for any character from a set.

💡 Best Practices

✅ Do

  • Use a writable char[] buffer
  • Implement a portable loop on cross-platform projects
  • Stop at '\0' when mimicking strnset
  • Use memset for zeroing entire structs or byte buffers
  • Keep n within the allocated buffer size

❌ Don’t

  • Assume strnset exists on GCC/Linux without checking
  • Pass string literals to modification functions
  • Use strnset to lengthen a string
  • Confuse string fill with secure secret wiping (use dedicated APIs)
  • Write past the buffer when n exceeds allocation

Key Takeaways

Knowledge Unlocked

Five things to remember about strnset()

Use these points when filling part of a string in C.

5
Core concepts
📝 02

Extension

Not ISO C.

Portability
🔢 03

Stops at null

Short str.

Behavior
📈 04

vs memset

Raw fill.

Compare
💬 05

In place

Writable.

Safety

❓ Frequently Asked Questions

strnset() replaces the first n characters of a string with a single character c (converted to char). It modifies the buffer in place and returns str. If the string is shorter than n, only characters up to the existing null terminator are changed.
No. strnset() is a compiler-specific extension found on some Microsoft and Borland toolchains. ISO C does not define it. Portable code uses a short loop or memset on a known prefix length.
char* strnset(char* str, int c, size_t n); The str argument must be a writable char array. c is the fill byte (often written as a character literal). n is the maximum number of positions to overwrite.
memset writes n bytes regardless of null terminators—it is for raw memory. strnset (where available) treats str as a C-string and typically stops at '\0' if the string ends before n characters.
strset() fills the entire string up to its null terminator with c. strnset() fills at most the first n characters. Both are non-standard extensions on many platforms.
No. String literals are read-only. Pass a writable char array such as char buf[] = "Hello";
Did you know?

Standard C gives you memset for filling bytes and strlen for measuring strings, but no built-in strnset. Many tutorials group strset and strnset with other DOS-era string helpers. When you see them in legacy source, check whether a simple loop or memset is the clearer modern replacement.

Continue the String Functions Series

Fill string prefixes with strnset() concepts, then search with strpbrk().

Next: strpbrk() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful