C:搜索数组并返回多个值

标签 c arrays search

我正在研究教科书中有关二维数组的示例。它有以下示例,允许用户输入一个值,然后搜索数组并返回包含该值的元素的位置,或者在该值不存在时发出警报。

我想知道,如果多个元素包含用户的值怎么办?在代码中,我添加了一些循环来初始化二维数组,并且多个元素包含相同的值。我将如何设置搜索以返回包含搜索值的多个元素?

#include <stdio.h>

int main() {

int iTwoD[3][3];
int iFoundAt[2] = {0};
int x, y;
int iFound, iValue = 0;


//initialize the 2-d array
for ( x = 0; x<=2; x++) {

  for (y=0;y<=2;y++)
    iTwoD[x][y] = (x+y);
} //end outer loop

//print the 2-d array
for (x=0; x<=2; x++){

  for (y=0;y<=2;y++)
    printf("iTwoD[%d][%d] = %d\n", x, y, iTwoD[x][y]);

}//end outer loop

//Get the user's value to search for
printf("\nEnter your search value: ");
scanf("%d", &iValue);

//Search the 2-d array for user's value
for (x = 0; x<=2; x++) {
  for (y = 0; y<=2; y++) {
    if ( iTwoD[x][y] == iValue) {
      iFound = 1;
      iFoundAt[0] = x;
      iFoundAt[1] = y;
      break;
    } //end if
  } //end inner loop
} //end outer loop

if (iFound ==1)
  printf("\nFound value in iTwoD[%d][%d]\n", iFoundAt[0], iFoundAt[1]);
else
  printf("\nValue not found\n");

return 0;
} //end main

最佳答案

if ( iTwoD[x][y] == iValue)
{
   arrayOfResults[i][0]=resultx;
   arrayOfResults[i++][1]=resulty;
}

关于C:搜索数组并返回多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15213209/

相关文章:

c fork 的子 ppid 与父的 pid 不匹配

c - C 中使用指针对数组进行排序时遇到的问题

java - 填充特定范围内的数组

database - 在向量中搜索计算量太大

c - dlopen() 搜索路径

c - C中的函数指针数组

c - 在 c 中重新打开 stdin、stdout 或 stderr

javascript - 数组洗牌,但保持相等值之间的距离

java - 如何设置程序的硬盘位置以供搜索或编辑? ( java )

mongodb - MongoDB 中数十亿小文档的快速搜索策略