Using typedef variable (C)

72 views Asked by At

Hello I am having some trouble using this variable in my program:

typedef char chessPos[2];

How exactly should I be scanning into it, using it in functions, and how would I properly make and use an array of this type?

to scan it i tried using:

scanf("%c%c", currPos[0], currPos[1]);

But I get this warning: scanf: format string %c requires an argument of type 'char*', but variadic argument 1/2 has type 'int'

thank you for your help!

2

There are 2 answers

0
pts On

This is one way:

chessPos currPos;
if (scanf("%c%c", currPos, currPos + 1) != 2) abort();

This is another way:

chessPos currPos;
int i;
if ((i = getchar()) == EOF) abort();
currPos[0] = i;
if ((i = getchar()) == EOF) abort();
currPos[1] = i;

Your original code didn't work, because the %c format specifier expects a char*, i.e. a pointer to a char, and currPos[1] is the value. We need its address instead, e.g. currPos + 1 or, equivalently, &currPos[1].

0
gulpr On

Newer typedef pointers or arrays. It is a very bad practice.

To get an address of the nth element of an array you need to:

  • use pointer arithmetic: array + n
  • use the & operator: &array[n]

In your case:

scanf("%c%c", &currPos[0], &currPos[1]);
/*  or */
scanf("%c%c", currPos, currPos +1);