在C ++中通过引用传递unsigned char数组

时间:2013-10-26 19:08:42

标签: c++ arrays pass-by-reference

一切!我正在实施一个学校项目遇到一些困难,我们正在实施Serpent密码。问题在于函数

setKey(unsigned char (&user_key[32]))

我想将一个大小为32的字节数组传递给我的函数,然后让我的函数对该数组的值执行各种操作。我打印的代码将无法编译,因为我收到了错误 -

no known conversion for argument 1 from ‘unsigned char (*)[32]’ to 
‘unsigned char (&)   [32]’

我查看了很多类似的帖子,我找到的解决方案似乎都没有导致我的代码编译,或者如果它编译,我做了我喜欢的。不幸的是,我不记得我上次编译代码的方式,但是当我这样做时,在函数setKey()中打印出user_key []的值给了我以下输出:

19, 0, 0, 0, 51, 0, 0, 0, 83, 0, 0, 0, 115, 0, 0, 0, 20, 0, 0, 0, 52, 0, 0, 0,
84, 0, 0, 0, 116, 0, 0, 0  

此外,当它正在运行时,它在打印出线后以段错误退出 “这是结束。我唯一的朋友,结束。”以及“堆栈粉碎检测”警告。简而言之,我的代码似乎有各种各样的错误。任何帮助将不胜感激!!

#include <iostream>
#include <math.h>

using namespace std;

class KeySchedule{

  int ip[64];
  int key_size;
  unsigned long long int k0;
  unsigned long long int k1;
  unsigned long long int k2;
  unsigned long long int k3;

public:

  KeySchedule(){

    /*The initial permutation. To be applied to the plaintext and keys.
      ip = {0, 32, 64, 96, 1, 33, 65, 97, 2, 34, 66, 98, 3, 35, 67, 99,
      4, 36, 68, 100, 5, 37, 69, 101, 6, 38, 70, 102, 7, 39, 71, 103,
      8, 40, 72, 104, 9, 41, 73, 105, 10, 42, 74, 106, 11, 43, 75, 107,
      12, 44, 76, 108, 13, 45, 77, 109, 14, 46, 78, 110, 15, 47, 79, 111,
      16, 48, 80, 112, 17, 49, 81, 113, 18, 50, 82, 114, 19, 51, 83, 115,
      20, 52, 84, 116, 21, 53, 85, 117, 22, 54, 86, 118, 23, 55, 87, 119,
      24, 56, 88, 120, 25, 57, 89, 121, 26, 58, 90, 122, 27, 59, 91, 123,
      28, 60, 92, 124, 29, 61, 93, 125, 30, 62, 94, 126, 31, 63, 95, 127};
    */

    for (int i = 0; i < 127; i++ ){
      ip[i] = (32*i) % 127;
    } 
    ip[127] = 127;

    k3 = 0; 
    k2 = 0; 
    k1 = 0;
    k0 = 0;  
    key_size = -1;
  }

  void setKey (unsigned char (&user_key)[32]){

    for (int i = 0; i<32; i++){
      cout << (int)(user_key)[i] << endl;
    }

    for (int i = 0; i<8; i++){
      k3 ^= (int)(user_key)[i] << (8-i);
      k2 ^= (int)(user_key)[i+8] << (8-i);
      k1 ^= (int)(user_key)[i+16] << (8-i);
      k0 ^= (int)(user_key)[i+24] << (8-i);
    }

  }
};

int main(){

   unsigned char testkey[]= {0x01, 0x02, 0x03, 0x04, 
                 0x05, 0x06, 0x07, 0x08, 
                 0x09, 0x0a, 0x0b, 0x0c, 
                 0x0d, 0x0e, 0x0f, 0x10,
                 0x20, 0x30, 0x40, 0x50, 
                 0x60, 0x70, 0x80, 0x90, 
                 0xa0, 0xb0, 0xc0, 0xd0, 
                 0xe0, 0xf0, 0x00, 0xff};

   cout << "The size of testkey is: " 
        << sizeof(testkey)/sizeof(*testkey) << endl;

   KeySchedule ks = KeySchedule();

   ks.setKey(&testkey);
   cout << "This is the end. My only friend, the end." << endl;
};

1 个答案:

答案 0 :(得分:3)

您传递的是unsigned char数组的地址,即指向unsigned char[32]的指针。你需要这个:

ks.setKey(testkey);