3

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

Avi_M
  • 33
  • 4
  • 2
    What do you want to do with that? `pos` is an uninitialized pointer, accessing it is undefined behavior. – mch May 12 '21 at 09:56

2 Answers2

3

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.

Lundin
  • 195,001
  • 40
  • 254
  • 396
2

In your code you define pointer to the two element char array. It does not allocate the memory for that array. If you dereference this pointer it leads to the Undefined Behaviour.

In your code ptr references the char array. When you *pos[1] you dereference the first element of the second char array not the second character in the array. To access second elements of the array you need to dereference pointer first and then use the index (*pos)[1]

You need to allocate the memory for the characters:

#include <stdio.h>
#include <stdlib.h>

typedef char chessPos[2];

int main(void)
{
    chessPos* pos;
    pos = malloc(sizeof(*pos));
    (*pos)[0] = 'C';
    (*pos)[1] = '3';

    printf("(*pos)[0] = '%c', (*pos)[1] = '%c'\r\n", (*pos)[0],  (*pos)[1]);
}

https://godbolt.org/z/8nPxn3TxE

or simple (without the pointer)

#include <stdio.h>

typedef char chessPos[2];

int main(void)
{
    chessPos pos;
    pos[0] = 'C';
    pos[1] = '3';

    printf("pos[0] = '%c', pos[1] = '%c'\r\n", pos[0],  pos[1]);
}

https://godbolt.org/z/h6fj7c1Ea

0___________
  • 60,014
  • 4
  • 34
  • 74