首页 > 解决方案 > 指针算术 - 计数点

问题描述

无法获得任何 if 语句来触发和打印主要内容。我对从这里做什么感到困惑。

你能找到我在这个问题上出错的地方吗?我需要计算点和破折号的数量(我已经将其简化为首先处理点)。

该问题必须使用指针算法来解决,并且已经提供了函数

void analyse(char* code, int* p_dots, int* p_dashes);

^

#include <stdio.h>
#include <string.h>

void analyse(char* code, int* p_dots)
{
char *current = code;
int k = 0;

if ((*current + k) == '.')
{
    p_dots++;
    k++;
}
if ((*current + k) == '-')
{
    //p_dashes++;
    k++;
}
if ((*current + k) ==' ')
{
    //p_dashes++;
    k++;
}
}

int main(void)
{
char* morse[] =
{
    "... --- ..."                           // SOS
//  "-- --- .-. ... .",                     // MORSE
//  "-.-. --- -.. .",                       // CODE
//  "-.-. --- -- .--. ..... ----- -----",   // COMP500
//  ". -. ... . ..... ----- .----"          // ENSE501
};

char* code = *morse;
int*p_dots=0;
//int*p_dashes = 0;

analyse(code, p_dots);

printf("Line 1 has %d dots", *p_dots);

return 0;
}

标签: c

解决方案


这是另一种方法:

#include <stdio.h>

void analyse(char *code, int *p_dots, int *p_dashes)
  {
  for( ; *code ; ++code)
    {
    if (*code == '.')
      *p_dots += 1;

    if (*code == '-')
      *p_dashes += 1;
    }
  }

int main(void)
  {
  int dots;
  int dashes;
  char *morse[] =
    {
    "... --- ...",                          // SOS
    "-- --- .-. ... .",                     // MORSE
    "-.-. --- -.. .",                       // CODE
    "-.-. --- -- .--. ..... ----- -----",   // COMP500
    ". -. ... . ..... ----- .----"          // ENSE501
    };

  for(int i = 0 ; i < sizeof(morse) / sizeof(char *) ; ++i)
    {
    dots = 0;
    dashes = 0;

    analyse(morse[i], &dots, &dashes);

    printf("Line %d ('%s') has %d dots and %d dashes\n", i, morse[i], dots, dashes);
    }

  return 0;
  }

指针是一个包含某物地址的变量。使用指针,您可以查看和/或更改它指向的东西。如果您增加指针,您正在更改指针中的地址,因此您正在更改它指向的内容。

在这段代码中,所有的指针运算都是在函数的for循环for( ; *code ; ++code)中完成的analyse。我们在这里要说的是 A) 没有初始化部分(语句中第一个之前没有代码);forB)只要在语句的“测试”部分中code指向指针的内容不为零,我们就希望继续;C)在每次循环之后,我们要增加指针(在语句的“增量”部分)。*codeforcode++codefor

如果您愿意,可以将for循环替换为analyse

while(*code <> 0)
  {
  if (*code == '.')
    *p_dots += 1;

  if (*code == '-')
    *p_dashes += 1;

  code += 1;
  }

在查看这样的代码时,我发现每当我看到与指针变量一起使用的星号时,在心理上说“指针对象”很有用 - 所以我将上面代码的第一行读为

While object of pointer "code" is not equal to zero...

然后下一行读为

if object of pointer "code" is equal to the character "period"
  then add one to object of pointer "p_dots"

if object of pointer "code" is equal to the character "dash"
  then add one to object of pointer "p_dashes"

add one to the variable "code"

而不是“指针的对象”,也许您可​​以将其读作“指针的目标”,以提醒自己指针指向某物,并且您正在操纵指针指向的内容,或者换句话说,您正在操纵指针“目标”。

我发现这种东西可以帮助我更多地理解基于指针的代码。也许这也会对你有所帮助。


推荐阅读