Search code examples
clinuxstringstring-function

How to use strset() in linux using c language


I can’t use strset function in C. I'm using Linux, and I already imported string.h but it still does not work. I think Windows and Linux have different keywords, but I can’t find a fix online; they’re all using Windows.

This is my code:

   char hey[100];
   strset(hey,'\0');   

ERROR:: warning: implicit declaration of function strset; did you meanstrsep`? [-Wimplicit-function-declaration] strset(hey, '\0');

^~~~~~ strsep


Solution

  • First of all strset (or rather _strset) is a Windows-specific function, it doesn't exist in any other system. By reading its documentation it should be easy to implement though.

    But you also have a secondary problem, because you pass an uninitialized array to the function, which expects a pointer to the first character of a null-terminated string. This could lead to undefined behavior.

    The solution to both problems is to initialize the array directly instead:

    char hey[100] = { 0 };  // Initialize all of the array to zero
    

    If your goal is to "reset" an existing null-terminated string to all zeroes then use the memset function:

    char hey[100];
    
    // ...
    // Code that initializes hey, so it becomes a null-terminated string
    // ...
    
    memset(hey, 0, sizeof hey);  // Set all of the array to zero
    

    Alternatively if you want to emulate the behavior of _strset specifically:

    memset(hey, 0, strlen(hey));  // Set all of the string (but not including
                                  // the null-terminator) to zero