【问题标题】:How to give a counter variable in a c-string to a function如何将 c 字符串中的计数器变量提供给函数
【发布时间】:2019-11-10 12:46:16
【问题描述】:

我在 main 中有一个函数,它从 main 函数中获取一个字符串。

在 main 我有以下代码:

int main(void)
{
  char string[] = "string" ;

  function(string);

  return 0;
}

在这个函数中,我有一个循环遍历字符串。当特定条件为真时,我调用另一个函数,该函数必须再次获取字符串以及计数器。

unsigned int function(char* string)
{
  int counter = 0;
  while (string[counter] == ...)
  {
     if (... some condition ...) 
       anotherFunction(&string, &counter)
  }
}

anotherFunction()的函数原型:

anotherFunction(char* string[], int* counter)

问题是如何在这个函数中处理带有计数器的字符串?

void anotherFunction(char* string[], int* counter)
{
  // ??? string[counter] // ???
}

【问题讨论】:

  • 这看起来像伪代码,你有什么可以编译给我们看的吗?
  • function中,不要将字符串的地址(指向指针)传递给anotherFunction,只传递原始字符串(指向char的指针)。然后在anotherFunction 中使用它,就像在function 中使用它一样。 anotherFunction的签名应该是void anotherFunction(char *, int *)
  • 如果这是真正的代码并且你解释了你需要它做什么,那么回答会容易得多。目前它是相当“理论上的”,并且似乎是从对字符串参数的错误理解开始的。因此,直接回答您的问题只会使这种误解永久化。也就是说,我们可以告诉您如何按原样访问字符串,但如果函数签名和调用更合理,您不太可能需要这样做。

标签: c arrays function pointers c-strings


【解决方案1】:

您将stringcounter 作为指针传递给anotherFunction(),因此要访问字符串中的字符,您需要取消对两者的引用:

*string[*counter]
^       ^

但是完全不清楚为什么要通过指针传递这些参数。在string 的情况下,几乎可以肯定这是一个错误。对于counter,只有在anotherFunction() 修改counter 并且该修改在调用函数中可见时才需要。

您似乎希望要么

void anotherFunction( char* string, int* counter)

然后

string[*counter]

void anotherFunction( char* string, int counter)

string[counter]

如果您确实想修改counter,最好只返回一个值:

int anotherFunction( char* string, int counter);

然后:

counter = anotherFunction( string, counter ) ;

【讨论】:

    猜你喜欢
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 2014-06-28
    相关资源
    最近更新 更多