我将一个2d数组传递给一个函数来打印输出,但我得到的输出是错误的
功能
void PrintArray(unsigned char mat[][4]){
int i, j;
printf("\n");
for(i = 0;i<4;i++){
for(j = 0;j<4;j++)
printf("%3x",mat[i][j]);
printf("\n");
}
printf("\n");
}
Run Code Online (Sandbox Code Playgroud)
主功能
int main(){
int i,j;
//static int c=175;
unsigned char state[4][4], key[4][4], expandedKey[176];
printf("enter the value to be decrypted");
for(i=0;i<4;i++)
for(j=0;j<4;j++)
scanf("%x",(unsigned int *)&state[j][i]);
PrintArray(state);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
预期产出
1 5 9 c
2 6 0 d
3 7 a e
4 8 b f
Run Code Online (Sandbox Code Playgroud)
实际产出
h2o@h2o-Vostro-1015:~$ ./a.out enter the value to be decrypted 1 2 3 4 5 6 7 8 9 0 a b c d e f
1 5 9 c
0 0 0 d
0 0 0 e
0 0 0 f
Run Code Online (Sandbox Code Playgroud)
我检查了传递2d数组的方法,我认为这是正确的,但不确定为什么得到这个输出,请建议...
我要走出去,说你的问题就在这里:
scanf("%x",(unsigned int *)&state[j][i]);
Run Code Online (Sandbox Code Playgroud)
state[i][j]大小只能容纳一个char,但你要告诉scanf它把它当作指针unsigned int; 这可能意味着scanf覆盖相邻的数组元素,因为sizeof (unsigned int)它很可能大于sizeof (char).
将数组的声明更改char为unsigned intin main和in PrintArray,并丢失强制转换scanf.