Himanshu Sourav
Himanshu Sourav

Reputation: 710

2 dimensional array in C language

I am passing a 2d array to a function to print the output, but the output I am getting is erroneous


function

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

main function

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

expected output

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

actual output

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

I checked the method of passing 2d array, its correct I think, but not sure why m getting this output, kindly advise...

Upvotes: 1

Views: 175

Answers (2)

Danke Xie
Danke Xie

Reputation: 1797

The array passing is correct. However, the scanf function seems to overwrite some values to be 0 due to the variable type %x.

The data type specified by %x is "int" because %x is like %d (except that the input is hexadecimal). The data occupies 4 bytes (typically). So when the user enters a number, say, 1, four bytes 01 00 00 00 (assuming little-endianness on an Intel machine) will be written to memory instead of 1. The trailing 0s will erase some existing elements that are stored in the byte array, because in the byte array, each element is allocated only 1 byte.

Try the following code:

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

Upvotes: 4

John Bode
John Bode

Reputation: 123468

I'm going to go out on a limb and say that your problem lies here:

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

state[i][j] is sized to hold a single char, but you're telling scanf to treat it as a pointer to unsigned int; this likely means that scanf is overwriting adjacent array elements, since sizeof (unsigned int) is most likely greater than sizeof (char).

Change the declaration of the array from char to unsigned int in both main and PrintArray, and lose the cast in scanf.

Upvotes: 6

Related Questions