Search code examples
arrayscpointerstypedef

typedef fixed size array in c not working properly


I have a typedef of a char array to represent the position of a chess piece.

typedef char chessPos[2];

yet when i attempt to create an array of this type i run into unexplained behaviours. for example.

  chessPos test= {'A','1'};
  chessPos test2= {'B','2'};
  chessPos* ptr = (chessPos*)(malloc(sizeof(chessPos) * 2));

  (*ptr)[0] = test[0];
  (*ptr)[1] = test[1];

  (*ptr+1)[0] = test2[0];
  (*ptr+1)[1] = test2[1];

  printf("(%c,%c)",*ptr[0],(*ptr)[1]);
  ptr++;
  printf("(%c,%c)",*ptr[0],(*ptr)[1]);

i will get:

(A,B)(2, ) 

instead of the expected:

(A,1)(B,2)

Solution

  • It's karma: write really strange code and the universe will give you really strange bugs as revenge...

    You have several issues with operator precedence. Fix it like this:

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef char chessPos[2];
    
    int main (void)
    {
      chessPos test= {'A','1'};
      chessPos test2= {'B','2'};
      chessPos* ptr = (chessPos*)(malloc(sizeof(chessPos) * 2));
    
      (*ptr)[0] = test[0];
      (*ptr)[1] = test[1];
    
      (*(ptr+1))[0] = test2[0];
      (*(ptr+1))[1] = test2[1];
    
      printf("(%c,%c)",(*ptr)[0],(*ptr)[1]);
      ptr++;
      printf("(%c,%c)",(*ptr)[0],(*ptr)[1]);
    }
    

    You should however salvage this unreadable code by dropping the typedef and use multi-dimensional indexing instead:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main (void)
    {
      char test[2]= {'A','1'};
      char test2[2]= {'B','2'};
      char (*ptr)[2] = malloc( sizeof(char[2][2]) );
    
      ptr[0][0] = test[0];
      ptr[0][1] = test[1];
      ptr[1][0] = test2[0];
      ptr[1][1] = test2[1];
    
      printf("(%c,%c)",ptr[0][0],ptr[0][1]);
      ptr++;
      printf("(%c,%c)",ptr[0][0],ptr[0][1]);
    }
    

    Always avoid hiding pointers and arrays behind typedefs!