Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem entering values to typedef char array in C

in my code I have this typedef char:

typedef char chessPos[2];

and when I try to debug and see the the values I try to enter

chessPos* pos;
*pos[0] = 'C';
*pos[1] = '3’;

after debugging I get that the values in the array are as such (not a string so I don’t need \0) for some reason the char ‘3’ isn’t in the array and I get \0 instead.

debugging

what can I do ? thanks

like image 511
Avi_M Avatar asked Mar 15 '26 20:03

Avi_M


1 Answers

You should avoid hiding arrays and pointers behind typedefs. It makes the code impossible to read and leads to curious, unintended side-effects.

In your case chessPos* is actually a char(*)[2] type and *pos[0] gives you pointer arithmetic on such an array pointer type, before de-reference.

Also you can't "store values inside a pointer", that doesn't make any sense. Pointers need to point at valid memory and the values stored in that pointed-at memory, see Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer

Drop the array type in the typedef. If you need a custom type, use a struct instead:

typedef struct
{
  char coord[2];
} chessPos;

chessPos pos = { 'C', '3' };

Please note that this is not a null terminated string either, so if you intend to use it as such, increase the size to 3 and do "C3" instead.

like image 189
Lundin Avatar answered Mar 18 '26 09:03

Lundin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!