I have the initializer for char array:
static const char dtmf_positions[] = "123A-------" "456B-------" "789C-------" "*0#D-------" "----E------" "-----F-----" "------G----" "-------H---" "--------J--" "---------K-" "----------L";
Can somebody explain, how to get some symbol by index, eg symbol '4'. Thank you.
Ok, then I have additional question. Is there any convenient way to access array elements by row and column index in above kind of array, like we do with two dimensional array?
From C99 specs, 5.1.1.2 Translation phases
- Adjacent string literal tokens are concatenated.
You can find similar text in other C specs also.
So
"abc" "def" would become "abcdef" during translation phase.
So your definition is similar to:
static const char dtmf_positions[] = "123A-------456B-------789C-------*0#D-----------E-----------F-----------G-----------H-----------J-----------K-----------L";
I hope now you can find index for any symbol :)
EDIT: Your additional question:
/* Col 012345678910 */
static const char dtmf_positions[] = "123A-------" /* Row 0 */
"456B-------" /* Row 1 */
"789C-------" /* Row 2 */
"*0#D-------" /* Row 3 */
"----E------" /* Row 4 */
"-----F-----" /* Row 5 */
"------G----" /* Row 6 */
"-------H---" /* Row 7 */
"--------J--" /* Row 8 */
"---------K-" /* Row 9 */
"----------L"; /* Row 10 */
#define NCOLS (sizeof("123A-------") - 1)
#define FETCH_CHAR(ROW,COL) dtmf_positions[ROW * NCOLS + COL]
After this you can access any character with FETCH_CHAR(R,C)
This is a single C literal. The language allows you to split string literals by adding quotes on both sides of a "gap", and inserting whitespace in between (demo):
char *s = "AB" "CD";
printf("%s\n", s);
is the same as
char *s = "ABCD";
printf("%s\n", s);
This is usually done for convenience when formatting your code: line breaks are allowed, too, so you can make parts of the literal appear in vertical columns:
static const char dtmf_positions[] = "123A-------"
"456B-------"
"789C-------"
"*0#D-------"
"----E------"
"-----F-----"
"------G----"
"-------H---"
"--------J--"
"---------K-"
"----------L";
So if you would like to find the index of character '4', start counting at zero, and skip over the "gaps" in your literal to get the index (you should get 11).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With