C-如何使用指针更轻松地指向字符串数组的开头

问题描述

我有一个功能。此功能旨在在称为客户应收帐款数据库的结构数组中遍历客户名称。该代码使用指针来引用结构数组,以访问数据库中每个索引处的每个客户名称。该代码应该先清除所有非字母字符,然后再将每个名称的首字母用大写字母表示。

/**********************************************************************/
/*     Titlecases and removes all nonletter characters from names     */
/**********************************************************************/
void clean_names(struct customer *p_customer_start,int customer_number)
{
   struct customer *p_last_name; /* Points to every customer          */
   char *p_fast,/* Points to customer's name         */
        *p_slow;                 /* Points to all letters             */

   for(p_last_name = p_customer_start;
      (p_last_name - p_customer_start) < customer_number; p_last_name++)
   {
      p_fast = p_last_name->last_name;
      p_slow = p_last_name->last_name;

      while(*p_fast != END_OF_STRING)
      {
         if(isalpha(*p_fast))
            *p_slow++ = tolower(*p_fast);
         p_fast++;
      }
      *p_slow = END_OF_STRING;
      *(p_slow-strlen(p_last_name->last_name)) =
      toupper(*(p_slow-strlen(p_last_name->last_name)));
   }
   return;
}

我在排队时很难过

*(p_slow-strlen(p_last_name->last_name)) = toupper(*(p_slow-strlen(p_last_name->last_name)));

struct customer一个字符数组char last_name[21]。我在使用指针指向字符数组中的第一项并将其大写时遇到麻烦。我使用的方法是我发现唯一可行的解​​决方案。 p_slow指向字符串末尾的NULL字符。我使用指针算术使用strlen()解除对p_slow - total string length的引用,使其指向数组p_last_name->last_name中的第一项。

我不是在寻找一个布局清晰的解决方案,而是在寻找简化代码的建议。

解决方法

您不需要该复杂的表达式即可找到名称的第一个字符。 p_last_name->last_name包含更新后的名称,因此您可以引用它来访问第一个字符。

*p_last_name->last_name = toupper(*p_last_name->last_name);