使用指向char数组指针的strcpy_s()的C++指针
问题描述:
我很关注我自己,但这里就是我所拥有的。我最近才开始熟悉指针,更多地指出我使用它们更舒适的一点,但是我发现strcpy_s()中的缓冲区太小。使用指向char数组指针的strcpy_s()的C++指针
请不要评论我使用char数组而不是std :: string,它以HL数组为中心(不知道为什么),所以我只是坚持使用模式。
void func_a()
{
char *szUserID = new char[64];
char *szInviterID = new char[64];
char *szGroupID = new char[64];
sprintf(szUserID, "%I64d", GetCommunityID(szUserSteamID));
sprintf(szInviterID, "%I64d", GetCommunityID(g_CvarSteamID.GetString()));
GetGroupCommunityID(1254745, &szGroupID); // Group Steam Community ID
}
void GetGroupCommunityID(int groupID, char **communityID)
{
int staticID = 1035827914;
int newGroupID = 29521408 + groupID;
char *buffer = new char[64];
snprintf(buffer, sizeof(buffer), "%d%d", staticID, newGroupID);
strcpy_s(*communityID, sizeof(*communityID), buffer);
delete buffer;
}
答
问题是您正在使用sizeof
这是一个编译时构造来确定*communityID
的运行时间长度。这将基本上解决到sizeof(char*)
。你想要的是*communityID
中可用的字节数/字节数。这些信息需要与价值
GetGroupCommunityID(1254745, &szGroupID, sizeof(szGroupID));
void GetGroupCommunityID(int groupId, char** communityID, size_t length) {
...
strcpy_s(*communityID, length, buffer);
}
此外,在本例中,双指针是不必要的,因为你不改变指针一起传递,只是它的内容。如果你正在使用常量的值(字符* szGroupID =新的char [64]),为什么不声明一个常量,其值为64,并使用这个值的单指针会做得很好为
GetGroupCommunityID(1254745, szGroupID, sizeof(szGroupID));
void GetGroupCommunityID(int groupId, char* communityID, size_t length) {
...
strcpy_s(communityID, length, buffer);
}
答
strcpy_s
的第二个参数是第一个参数指向的缓冲区的实际大小(字符数)。 sizeof(*communityID)
只给你一个char *
指针的大小,通常是32位系统上的4个字节。您需要将*communityID
的实际大小传递给GetGroupCommunityID
函数,并将其传递给strcpy_s
。
答
;顺便说一下,sizeof(szGroupID)将在32位编译器中返回4个字节。
如果你需要一个动态分配的`char`数组,你通常可以使用`std :: vector`离开。我不明白为什么这不起作用。 –
2010-11-23 01:47:07
为什么新建和删除可以在堆栈中声明的完美的char缓冲区? – 2010-11-23 03:46:31