【发布时间】: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