问题描述
请考虑以下代码:
char CeaserCrypt(char str [256],int key)
{
char encrypted [256],encryptedChar;
int currentAsci;
encrypted [0] ='\0';
for(int i = 0; i {
currentAsci =(int)str [i]
encryptedChar =(char)(currentAsci + key);
encrypted [i] = encryptedChar;
}
return encrypted;
}
Visual Studio 2010给出错误,因为函数返回一个数组。我应该怎么办?
我的朋友告诉我将签名更改为 void CeaserCrypt(char str [256],char encrypted [256] int key)
。但我不认为这是正确的。如何摆脱编译错误?
返回类型应为 char * code>,但这只会增加另一个问题。
加密
CeaserCrypt
,并且在函数返回时可能不是有效的。由于加密
与输入的长度相同,请执行:
int len = strlen(str);
char * encrypted =(char *)malloc(len + 1);
encrypted [len] ='\0';
for(int i = 0; i // ...
}
pre>
不要忘记稍后释放缓冲区,尽管( free()
)。
编辑: @ Yosy:不必只是复制/粘贴。使用它作为指针以改善您的编码实践。此外,要满足批评者:使用上述示例传递已分配的加密例程的指针。
Consider the following 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 gives an error because the function returns an array. What should I do?
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?
解决方案 The return type should be char *
but this'll only add another problem.
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++) {
// ...
}
Don't forget to deallocate the buffer later, though (with free()
).
EDIT: @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 ++错误 - 返回一个字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!