1

想象一下,我有一个 C 语言程序,它给了我一个字符串。例如,“stackoverflow 岩石”。

现在我想在 Assembly 中创建一个函数,该函数将计算例如字母“o”在我的字符串中出现的次数。

该函数将在 C 程序中调用。

我正在考虑用 C 语言创建一个程序,让我做到这一点,然后通过标志 -s 将其转换为汇编。

[编辑]好的,我这样做了:

#include<stdio.h>

int FindChar(char *ptr, char toFind);

int FindChar(char *ptr, char toFind){

    int num;

    for (int i=1; ptr[i]=0; i++)
        if (ptr[i] = toFind){
            num++;
        }

    return(num);
}

int main ( ) {

    char str[]=”stackoverflow rocks”; 
    char tf=”o”; 
    printf(“It appears %d times \n”, FindChar(str,tf));
}

我的功能有什么问题?

4

1 回答 1

1

我认为您的备用双引号字符导致错误,加上您的初始化char tf应该使用单引号,而不是双引号,因为它是一个字符而不是字符串。

正如harold之前指出的那样,=需要是 a ==,因此它可以正常用作比较。

您也不需要额外的i变量,您只需推进指针即可。既然您无论如何都想要汇编代码,它应该使它更短一些,并且在技术上也更有效。

此代码修复了错误,并且在功能上也应该是正确的:

#include<stdio.h>

int FindChar(char *ptr, char toFind);

int FindChar(char *ptr, char toFind){
  int num = 0;
  for ( ; *ptr != '\0'; ++ptr)
    {
      if (*ptr == toFind){
        ++num;
      }
    }
  return(num);
}

int main ( ) {
  char str[]="stackoverflow rocks";
  char tf='o';
  printf("It appears %d times \n", FindChar(str,tf));
}
于 2013-04-15T16:48:51.750 回答