【问题标题】:How to iterate through multiple arrays for every position in the first array iterate the second array? [closed]如何为第一个数组中的每个位置迭代多个数组迭代第二个数组? [关闭]
【发布时间】:2017-12-09 09:16:58
【问题描述】:
#include "stdafx.h"
#include <stdio.h>
#include "iostream"

char s[100];
char s1[100];

int i = 0;
int i1 = 0;
int i2 = 0;

void populate();
void squeeze();

int main()
{
  printf("Write something, hit enter and than write something again. Hit 
  enter to see result\n");

  populate();
  squeeze();

  system("pause");

  return 0;
}

void populate()     // insert chars in two arrays
{
  int c;

  while ((c = getchar()) != '\n')
  {
      s[i] = c;
      i++;
  }

  while ((c = getchar()) != '\n')
  {
      s1[i1] = c;
      i1++;
  }
}

void squeeze()      // iterate the arrays to find if there are same chars
{
  char s2[1000];
  i = 0;
  i1 = 0;

  for (int r = 0; r <= s[i - 1]; r++)
  {
      for (int j = 0; j <= s1[i1 - 1]; j++)
      {
        if (s[r] == s1[j])
        {
            s2[i2] = s[r];
            i2++;
        }
      }
  }
  for (int m = 0; m <= s2[i2 - 1]; m++)    //print every element in s2[];
  {
      printf("%c", s2[m]);
  }
}

我想为第一个数组s 中的每个元素遍历第二个数组s1,并将重复项放入第三个数组s2
到目前为止,我在网上发现的只是如何遍历同一位置的两个或多个数组arr1[i] = arr2[i]arr1[i1] = arr2[i1] 等等。这是我的代码,但由于未知原因,它不起作用。

【问题讨论】:

  • 错别字:squeeze() 中的 i1 = 0 应该是 i2 = 0。顺便说一句,a &lt;= b - 1a &lt; b 的整数相同
  • 除非绝对必要,否则避免使用全局变量。 (在学习 C 时永远不会)全局变量增加了名称冲突和变量阴影问题的风险。随着代码大小的增加,这种情况变得更加严重。相反,在main() 中声明所需的变量并根据需要将它们作为参数传递。 (将-Wshadow 选项添加到编译字符串也是一个好主意)虽然全局变量有其位置,但它们的使用应该是一个罕见的例外而不是规则。
  • 谢谢,我会记住的
  • 你应该写#include &lt;iostream&gt;而不是#include "iostream"

标签: c arrays loops for-loop


【解决方案1】:
  i = 0;
  i1 = 0;

您正在丢失数组ss1 的长度。然后你访问数组索引越界调用未定义的行为。(在squeeze中)。

正确的做法是

void squeeze(void)      // iterate the arrays to find if there are same chars
{
  char s2[1000];

  for (size_t r = 0; r < i; r++)
  {
      for (size_t j = 0; j < i1; j++)
      {
        if (s[r] == s1[j])
        {
            s2[i2] = s[r];
            i2++;
        }
      }
  }
  for (size_t m = 0; m < i2; m++)    //print every element in s2[];
  {
      printf("%c", s2[m]);
  }
}

注意几点:

  • 这里不需要使用全局变量。您自己犯了修改全局变量的错误。随着时间的推移,在大型代码中使用过多的全局变量会降低其可维护性和可读性。

  • 知道如何在函数中传递参数。还可以查看 fgets 之类的函数,这些函数在您的案例中用于输入目的。

  • 检查这两个资源。这些对你有很大帮助

    1. how-to-debug-small-programs
    2. Definitive C books

【讨论】:

  • 是的...这给了我正确的结果。再次感谢。
猜你喜欢
  • 2019-04-26
  • 2018-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-06
  • 1970-01-01
  • 2023-01-08
  • 1970-01-01
相关资源
最近更新 更多