【问题标题】:Using a while loop to iterate through a char array received as a parameter in C使用 while 循环遍历作为 C 中的参数接收的 char 数组
【发布时间】:2016-02-02 21:53:55
【问题描述】:

我对 C 语言还是有点陌生​​,过去我一直坚持的一个问题是遍历作为参数接收的 char 数组。 char 数组被创建为字符串文字并作为参数传递。据我了解,这个数组被简单地接收为指向数组中第一个元素的指针;我的目标是遍历每个元素,直到到达所传递的字符串文字的末尾。

由于我需要在循环内执行每个 char 与 char 文字的比较,我已将数组中指向的值分配给用于比较的 char 变量。

我遇到问题的地方是指定该循环应该在什么时候结束。

int main (int argc, char* argv[])
{
    testString("the quick brown fox jumped over the lazy dog");

    return EXIT_SUCCESS;
}

void testString(char line[])
{
    int i = 0;
    int j = 0;
    char ch;
    ch = line[i];

    char charArray[128];

    while (ch != '\0')    // Not sure why this doesn't work
    {   

        if ((ch == '\'' || ch == '-'))
        {
            charArray[j] = ch;
            j++;
        }
        else if (isalpha(ch))
        {
            charArray[j] = ch;
            j++;
        }
        else
        {
             // do nothing
        }

        i++;
        ch = line[i];
    }
}

提前感谢您提供的任何建议。

【问题讨论】:

  • 了解如何使用调试器
  • 当循环找到字符串的结束标记时,程序将终止。字符串的结尾用 '\0' 表示。
  • 它不起作用是什么意思?看起来循环终止得很好——你只是不对生成的charArray 做任何事情。 (请注意,如果/当您使用 charArray 执行某些操作时,您可能需要确保它以现在没有发生的空字符正确终止。
  • @pm100 它已经在循环中,虽然缩进很严重。
  • 检查j 不超过charArray 的范围可能是明智的 - 即127。

标签: c arrays string loops pointers


【解决方案1】:

循环的退出条件工作正常。

唯一缺少的是您需要在 while 循环之后空终止 charArray 并将其打印出来:

while (ch != '\0')
{
    ...
}
charArray[j] = '\0';
printf("charArray=%s\n",charArray);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-13
    • 2011-10-30
    • 1970-01-01
    • 2018-09-18
    • 2011-08-23
    • 2021-06-20
    • 2013-05-15
    • 1970-01-01
    相关资源
    最近更新 更多