Home > Blockchain >  Function strnset() in C and how to use it
Function strnset() in C and how to use it

Time:02-21

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

int main(){
    
    char str1[30], str2[30];
    
    printf("Enter First String: ");
    gets(str1);
    
    printf("Enter Second String: ");
    gets(str2);
    
    printf("\n");
    printf("________________________");
    printf("\n");
    
    int result = strncmp(str1, str2, 1);
    
    if(result == 0){
        strnset(str1,("%s",str1[strlen(str1)-1]),1);
        strnset(str2,("%s",str2[strlen(str2)-1]),1);
        printf("Altered Strings");
        printf("\n");
        printf("First String: %s",str1);
        printf("\n");
        printf("Second String: %s",str2);
    }else{
        printf("Concatenated Strings:\n%s %s",str1,str2);
    }
    
    return 0;
}

Sample Output 1:

Enter First String: love
Enter Second String: lost
________________________
Altered Strings
First String: eove
Second String: tost

Sample Output 2:

Enter First String: programming
Enter Second String: is very easy
________________________
Concatenated Strings:
programming is very easy

Can someone explain this code?

strnset(str1,("%s",str1[strlen(str1)-1]),1);
strnset(str2,("%s",str2[strlen(str2)-1]),1);

CodePudding user response:

You are either ignoring compiler warnings (don't — the compiler doesn't complain unless it spotted a bug in your code) or you aren't compiling with enough warnings enabled (or, possibly, you are using an ancient and unhelpful C compiler).

The lines you ask about are basically the same:

strnset(str1, ("%s", str1[strlen(str1)-1]), 1);

The second argument to strnset() is ("%s", str1[strlen(str1)-1]), which is a comma-expression, and there is no side-effect in the LHS, so your compiler should be warning about something like that. A better, simpler way of writing that call would be:

strnset(str1, str1[strlen(str1)-1], 1);

That probably copies the last character of the string over the first character of the string. Certainly, str1[strlen(str1)-1] is the last character in the string. This is presumably somewhat similar to using either:

memset(str1, str1[strlen(str1)-1], 1);
str1[0] = str1[strlen(str1)-1];

The strnset() function is neither a part of the Standard C library nor a part of POSIX. IBM documents it, but the Linux manual pages don't seem to do so. […time passes…] Ah, Microsoft documents strnset() and _strnset() as being Microsoft-specific.

  • Related