C ++的错误 - 返回字符数组 [英] C++ error - returning a char array
问题描述
考虑以下code:
char CeaserCrypt(char str[256],int key)
{
char encrypted[256],encryptedChar;
int currentAsci;
encrypted[0] = '\0';
for(int i = 0; i < strlen(str); i++)
{
currentAsci = (int)str[i];
encryptedChar = (char)(currentAsci+key);
encrypted[i] = encryptedChar;
}
return encrypted;
}
Visual Studio 2010中,因为该函数返回一个数组给出了一个错误。我应该怎么办?
Visual Studio 2010 gives an error because the function returns an array. What should I do?
我的朋友告诉我改签名,以无效CeaserCrypt(加密字符海峡[256],CHAR [256],INT键)
。但我不认为这是正确的。我怎样才能摆脱编译错误的?
My friend told me to change the signature to void CeaserCrypt(char str[256], char encrypted[256], int key)
. But I don't think that is correct. How can I get rid of the compile error?
推荐答案
的返回类型应该是的char *
但这只会增加的另一个问题。
The return type should be char *
but this'll only add another problem.
加密
是 CeaserCrypt
的堆栈的分配,并可能不是当函数返回时有效。由于加密
将具有相同长度的输入,这样做:
encrypted
is "allocated" on the stack of CeaserCrypt
and might not be valid when the function returns. Since encrypted
would have the same length as the input, do:
int len = strlen(str);
char *encrypted = (char *) malloc(len+1);
encrypted[len] = '\0';
for (int i = 0; i < len; i++) {
// ...
}
不要忘了以后释放缓冲区,但(与免费()
)。
编辑: @Yosy:不觉得有义务只是复制/粘贴。使用此作为的指针的提高你的编码实践。此外,为了满足批评家:使用上述已经分配的指针传递给你的加密例程的例如的
@Yosy: don't feel obliged to just copy/paste. Use this as a pointer to improve your coding practice. Also, to satisfy criticizers: pass an already allocated pointer to your encryption routine using the above example.
这篇关于C ++的错误 - 返回字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!