命令行参数给出无效的初始化错误

时间:2014-07-19 04:21:56

标签: c command-line

以下是我正在处理的代码的一部分,其中我传递要加密的文件的名称,并使用命令行参数通过命令行分配密钥。

void encrypt(const char *fileIn, const char *fileOut,
const unsigned char *key);

int main(int argc, char *argv[]) 
{

 const unsigned char key[] = argv[3];
 srand(time(NULL));

 aes_init();
 encrypt(argv[1], "/home/ankita/python/encrypt/outfile.encrypted", key);

 return 0;

}

void encrypt(const char *fileIn, const char *fileOut, 
const unsigned char *key) {
int i;
aes_encrypt_ctx ctx[1];
unsigned char iv[16]; /* initialisation vector */
unsigned char inBuffer[200], outBuffer[200];
FILE *inFile = fopen(fileIn,"rb");
FILE *outFile = fopen(fileOut, "wb");

/* pick a random initialisation vector */
for(i = 0; i < 16; ++i)
iv[i] = rand() & 0xFF;
fwrite(iv, 1, 16, outFile);

aes_encrypt_key256(key, ctx);
while((i = fread(inBuffer, 1, sizeof(inBuffer), inFile)) > 0) {
aes_ofb_crypt(inBuffer, outBuffer, i, iv, ctx);
fwrite(outBuffer, 1, i, outFile);
}
aes_ofb_crypt(inBuffer, outBuffer, i, iv, ctx);
fwrite(outBuffer, 1, i, outFile);

fclose(inFile);
fclose(outFile);
}

现在,每当我尝试编译此代码时,这就是它给出的错误:

In function ‘main’:
error: invalid initializer

问题与我分配密钥或通过命令行参数传递文件名有关吗?如果是,请帮助您正确地做到这一点!

1 个答案:

答案 0 :(得分:0)

const unsigned char key[] = argv[3];

您无法分配,因为只有常量表达式可用于初始化数组。为此你需要char指针。因为argv[3]在编译时包含未知/解析的内容。

const unsigned char *key = argv[3];