简体   繁体   中英

C strncat function

someone know what is the problem in my code?

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

#define MAX_LEN 10
void printMessage(char str[]);

int main(void)
{
    char str[MAX_LEN] = "THANK ";
    char you = 'u';
    strncat(str, you, 1); // do not fix this line or the next one
    printMessage(str);
    return 0;
}

The error that I get is:

strncat: this function or variable may be unsafe, consider using strnact_s in stead.

However, I want to use this function strncat .

You probably got this error message:

Error C4996 'strncat': This function or variable may be unsafe. Consider using strncat_s instead.
To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

To remove the warning you can put #define _CRT_SECURE_NO_WARNINGS at the start of your code.

Furthermore this is wrong:

char you = 'u';

because the second parameter of strncpy is a pointer to char and not a char. Change it to:

char you[] = "u";

As an alternative you could also leave char you = 'u' and call strncat like this:

strncat(str, &you, 1);

If you don't wanna get the warning C4996 then tell Visual Studio that you don't want that warning.

You can do it in many ways.

Since I like portable C code and therefore I don't want to add #pragmas in my source files, I prefer telling Visual Studio to disable that specif warning.

Just disable warning C4996, as showed in the picture:

禁用:4996

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM