在 C 中使用紧凑指针寻址二维数组的元素

Addressing elements of 2-dimensional array using compact pointer in C

我正在使用 C 和 运行 将摩尔斯电码应用到一些基础知识中。

基本思路是我有一个从 A 到 Z 的二维字符数组。每个数组的第一个元素是一个字母表,后跟相应的摩尔斯电码。程序将收到一个字符,一旦找到匹配项,该字符将通过整个数组进行解析,我将吐出摩尔斯电码。我能够 运行 这个程序使用简单数组操作的帮助,但我 运行 遇到紧凑数组的问题。

数组定义如下,

char *morseKey[37] = { 
    {"A.-"},
    {"B-..."},
    {"C-.-."},
    {"D-.."},
    {"E."},
    {"F..-."},
    {"G--."},
    {"H...."},
    {"I.."},
    {"J.---"},
    {"L.-.."},
    {"K-.-"},
    {"L.-.."},
    {"M--"},
    {"N-."},
    {"O---"},
    {"P.--."},
    {"Q--.-"},
    {"R.-."},
    {"S..."},
    {"T-"},
    {"U..-"},
    {"V...-"},
    {"W.--"},
    {"X-..-"},
    {"Y-.--"},
    {"Z--.."}
};

常规二维数组实现,

/*
    Find a match for each character from nameCode string that need to be 
    transformed to Morse Code. Once the match is found then based on the 
    Morse code flash the LED for dash and dot.
*/
for(char *cp_nameCode = &nameCode[0]; *cp_nameCode != '[=11=]'; cp_nameCode++)
{
    charLoc = GetMorseCode(morseKey, first, last, *cp_nameCode);
    for(int col = 1; cp_morseKey[charLoc][col] != '[=11=]'; col++)
    {
        cp_morseKey[charLoc][col] == '.' ? dot() : dash();            
    }
}

现在我的方法是声明一个指向这个数组的指针,如下所示,

char **cp = morseCode;

然后在*cp 和**cp 的帮助下按顺序访问列和行。但是没用。

或者,我尝试声明,

char **cp = morseCode;
char *cp_row = *morseCode;

然后访问如下,

while(*cp != '[=14=]')
{
    while(*cp_row != '[=14=]')
    {
        //printf("%c\n", **cp++);
        printf("%c\n", *cp_row++);
    }
    cp_row = *((++*cp));
    //cp++;
}

但是代码没有超出第一行。感觉自己的指针知识还有差距

我将不胜感激解决此瓶颈的任何指示。

您可以通过使用要编码为数组中的索引的字母来简化查找 table。例如(未经测试,没有“防弹”或错误检查,仅适用于大写字母 A..Z):

#define NELMS(A) A/sizeof(A[0])

char *morseKeys[] = { 
    ".-",
    "-...",
    "-.-.",
    "-..",
    ".",
    "..-.",
    "--.",
    "....",
    "..",
    ".---",
    ".-..",
    "-.-",
    ".-..",
    "--",
    "-.",
    "---",
    ".--.",
    "--.-",
    ".-.",
    "...",
    "-",
    "..-",
    "...-",
    ".--",
    "-..-",
    "-.--",
    "--.."
};

char *encodeLetter(char letter) {
  return morseKeys[letter - 'A'];
}

char decodeLetter(char *code) {
  // Search array
  for (int i=0; i < NELMS(morseKeys); i++) {
    if (strcmp(morseKeys[i], code) == 0)
      return 'A' + i;
  }
  // Not found
  return 0;
}

希望能有所帮助……至少有一点帮助。

问:获得正确的莫尔斯字符串(例如“-...”)后,您还需要进行哪些额外处理?从你的代码中我不清楚你还需要做什么(如果有的话)。


在上面的例子中,我试图展示:

  • 您不需要在您的 morseKey[] 值中包含字母(例如“A”)
  • 您不需要指定数组长度(“37”),并且
  • 您不一定需要“循环”来搜索数组。例如,“encodeLetter()”通过使用字母作为索引值进行“直接查找”。快多了。

回答你的另一个问题:如果你想用 char** 指针迭代 morseKey[] 值,你会做这样的事情:

char *strings[] = { "AAA", "BBB", "CCC", 0 };
char **pp = strings;
while (*pp)
  printf ("value: %s\n", *pp++);