[英]Copying a C-style string into memory allocated on free store?
我正在做一個練習,其中我必須將c樣式的字符串復制到免費存儲中分配的內存中。 我必須不使用下標並僅依靠指針算術來做到這一點。 我寫了以下函數-
char* str_dup(const char* s)
{
// count no. of elements
int i = 0;
const char* q = s;
while (*q) { ++i; ++q; }
//create an array +1 for terminating 0
char* scpy = new char[i + 1];
//copy elements to new array
while (*s)
{
*scpy = *s;
++s;
++scpy;
}
*scpy = 0;
return scpy;
}
該函數返回隨機字符。 但是如果我將其更改為
char* str_dup(const char* s)
{
// count no. of elements
int i = 0;
const char* q = s;
while (*q) { ++i; ++q; }
//create an array +1 for terminating 0
char* scpyx = new char[i + 1];
char* scpy = scpyx;
//copy elements to new array
while (*s)
{
*scpy = *s;
++s;
++scpy;
}
*scpy = 0;
return scpyx;
}
有用。 有人可以解釋一下為什么第一個代碼不起作用而第二個代碼卻起作用嗎?
第一個代碼不起作用,因為您返回了scpy
的最終值,該值此時指向終止NUL字符,而不是字符串的開頭。
一種解決方案是像您一樣做,並保存原始指針的副本以返回某些內容。
您應該真正使用strlen()
和memcpy()
,它們使此操作更容易,但可能對您來說是不可行的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.