簡體   English   中英

C語言中的二維數組

[英]2 dimensional array in C language

我將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");
}

主功能

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;
}

預期產量

  1  5  9  c   
  2  6  0  d 
  3  7  a  e
  4  8  b  f

實際產量

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

我檢查了傳遞2d數組的方法,我認為它是正確的,但是不確定為什么要獲得此輸出,請告知...

我要彎腰說你的問題就在這里:

scanf("%x",(unsigned int *)&state[j][i]);

state[i][j]的大小可容納單個char ,但是您要告訴scanf將其視為指向unsigned int的指針; 這很可能意味着scanf正在覆蓋相鄰的數組元素,因為sizeof (unsigned int)最有可能大於sizeof (char)

mainPrintArray中將數組的聲明從char更改為unsigned int ,並在scanf丟失PrintArray

數組傳遞正確。 但是,由於變量類型%x,scanf函數似乎將某些值覆蓋為0。

%x指定的數據類型為“ int”,因為%x類似於%d(輸入為十六進制除外)。 數據占用4個字節(通常)。 因此,當用戶輸入數字(例如1)時,會將四個字節0​​1 00 00 00(假設在Intel計算機上為little-endianness)寫入內存,而不是寫入1。結尾的0將擦除存儲在內存中的某些現有元素。字節數組,因為在字節數組中,每個元素僅分配了1個字節。

嘗試以下代碼:

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");
int tmp;
for(i=0;i<4;i++)
    for(j=0;j<4;j++) {
        scanf("%x", &tmp);
        state[j][i] = (char)tmp;
    }
PrintArray(state);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM