我尝试在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;
}发布于 2014-09-23 00:59:01
问题在于您的函数声明:
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)https://stackoverflow.com/questions/25985174
复制相似问题