且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++错误 - 返回一个字符数组

更新时间:2023-11-17 17:55:52

返回类型应为 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.