我已经尝试在 C++ 中实现我自己的复制字符串功能
void pcstrdup(const char* szStr, char* szStrCpy)
{
int nLen = strlen(szStr);
if (!nLen)
throw "Error : attempt copying an empty string";
++nLen;
szStrCpy = static_cast<char*>(malloc(sizeof(char) * nLen));
if (!szStrCpy)
throw "Error : memory allocation failed";
for (int i = 0; i < nLen; i++)
{
szStrCpy[i] = szStr[i];
}
}
我已经调试并检查了正在复制的字符,它复制了除\0 字符以外的所有字符,当它到达那个点时我得到一个异常
Unhandled exception at 0x011A5BA1 in assignment2.exe: 0xC0000005: Access violation reading location 0x00000000.
这让我想到了这个功能:
static size_t __CLRCALL_OR_CDECL length(const _Elem *_First)
{ // find length of null-terminated string
return (*_First == 0 ? 0
: _CSTD strlen(_First));
}
请注意,istrlen() 函数是我编写的函数。
int istrlen(const char* szStr)
{
int count = 0;
for (int i = 0; szStr[i] != NULL; i++)
{
++count;
}
return count;
}
最佳答案
问题出在你的函数声明中:
void pcstrdup(const char* szStr, char* szStrCpy)
当您分配szStrCpy
内存时,调用者看不到变化,因为指针是按值传递的。当您的 pcstrdup
返回时,分配给 szStrCpy
的内存丢失,调用者看到旧值(在这种情况下,它看起来像 NULL
).
您可以通过引用传递 szStrCpy
来解决此问题:
void pcstrdup(const char* szStr, char *&szStrCpy)
更好的是,您应该返回 szStrCpy
而不是将其作为第二个参数:
char *pcstrdup(const char* szStr)
关于c++ - 复制字符串函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25985174/