我想我理解了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