您的位置:首页 > 其它

strcpy_s 用法 及 指针数组的理解

2011-02-28 16:40 435 查看
正确用法:

int n = 6;
char **argsmy = new char *
;
int maxlen = 600;
for(int i = 0; i < n; i ++)
{
argsmy[i] = new char [maxlen];// args[i];
}
strcpy_s(argsmy[1],maxlen,"e");
strcpy_s(argsmy[2],maxlen,"Lzma_");
strcat_s(argsmy[2], 600, cTAppEncTop.getBitstreamFile());
strcpy_s(argsmy[3],maxlen,"-BS12");
strcpy_s(argsmy[4],maxlen,"-CN0");
strcpy_s(argsmy[5],maxlen,"-d15");

错误用法:

argsmy[2] = "Lzma_"; strcpy_s(argsmy[2],maxlen,"see");

原因:

argsmy[2] = "Lzma_"; //因为 argsmy[2] 是个指针。他指向一块分配的空间 ,长度 maxlen。

而这样赋值后,指针指向位置变了。而再strcpy_s(argsmy[2],maxlen,"see"); 实际上是将常数变量空间强制赋值。因此出问题。

strcpy_s 用法:

errno_t strcpy_s(
char *strDestination,
size_t numberOfElements,
const char *strSource
);

template <size_t size>
errno_t strcpy_s(
char (&strDestination)[size],
const char *strSource
); // C++ only
例子:

C/C++ code
// crt_strcpy_s.cpp
// This program uses strcpy_s and strcat_s
// to build a phrase.
//

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

int main( void )
{
char string[80];
// using template versions of strcpy_s and strcat_s:
strcpy_s( string, "Hello world from " );
strcat_s( string, "strcpy_s " );
strcat_s( string, "and " );
// of course we can supply the size explicitly if we want to:
strcat_s( string, _countof(string), "strcat_s!" );

printf( "String = %s/n", string );
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: