我想我理解了this question的答案,但我不知道。我理解第一个结果,但我仍然不知道如何正确地复制副本。我尝试下面的代码:将一个字符串复制到一个malloc'd数组字符串
// TstStrArr.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string.h>
#include <malloc.h>
int main()
{
char ** StrPtrArr;
char InpBuf0[] = "TstFld0";
char InpBuf1[] = "TstFld1";
StrPtrArr = (char **)malloc(2 * sizeof(char *));
StrPtrArr[0] = (char *)malloc(10 + 1);
printf("inpbuf=%s sizeof=%2d ", InpBuf0, sizeof(StrPtrArr[0]));
strncpy_s(StrPtrArr[0], sizeof(StrPtrArr[0]), InpBuf0, _TRUNCATE);
printf("strptrarr=%s\n", StrPtrArr[0]);
StrPtrArr[1] = (char *)malloc(10 + 1);
printf("inpbuf=%s sizeof=%2d ", InpBuf1, sizeof(*StrPtrArr[1]));
strncpy_s(*StrPtrArr[1], sizeof(*StrPtrArr[1]), InpBuf1, _TRUNCATE); // error here
printf("*strptrarr=%s\n", StrPtrArr[1]);
free(StrPtrArr[0]);
free(StrPtrArr[1]);
free(StrPtrArr);
return 0;
}
我得到的结果是:
inpbuf=TstFld0 sizeof= 4 strptrarr=Tst
inpbuf=TstFld1 sizeof= 1
,并出现以下错误:
Exception thrown: write access violation.
destination_it was 0xFFFFFFCD.
我想我会得到要么的结果以下:
inpbuf=TstFld1 sizeof=11 *strptrarr=TstFld1
inpbuf=TstFld1 sizeof= 1 *strptrarr=T
我明白第一个拷贝将输入缓冲区复制到4字节的指针,这是不正确的。我认为第二个副本会将输入缓冲区复制到大小为11的解除引用指针的值,但它没有。我猜测该副本是数组中字符串的第一个字符。我不明白内存足以知道地址0xFFFFFFCD的意义,但我想它是在只读内存,从而导致错误。
复制的正确方法是什么?
(我不认为它很重要,但我使用VS 2015年社区版更新3)
的sizeof不会给你字符串的长度。 – koper89
谢谢。确实如此。我相信'strncpy'的MS版本的第二个参数需要是接收器变量的sizeof。 –
什么是_TRUNCATE?它看起来不像正确使用'strncpy_s'。请参阅[规范](http://port70.net/~nsz/c/c11/n1570.html#K.3.7.1.4) – Olaf