用指针方法在数组中找元素,若找到则输出在中的位置,否则输出“没有找到”
时间: 2024-03-14 10:44:58 浏览: 30
好的,这是一个简单的 C 语言问题。以下是示例代码:
```c
#include <stdio.h>
int findElement(int *arr, int size, int element) {
for (int i = 0; i < size; i++) {
if (*arr == element) {
return i;
}
arr++;
}
return -1;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int element = 3;
int index = findElement(arr, size, element);
if (index == -1) {
printf("没有找到\n");
} else {
printf("元素 %d 在数组中的位置是 %d\n", element, index);
}
return 0;
}
```
在这个例子中,我们定义了一个 `findElement` 函数来寻找数组中指定的元素。该函数接受三个参数:一个指向数组的指针,数组的大小和要查找的元素。在函数内部,我们使用 `for` 循环遍历数组并检查每个元素是否等于要查找的元素。如果找到了元素,函数将返回该元素在数组中的索引。如果没有找到元素,函数将返回 `-1`。在 `main` 函数中,我们将一个整数数组传递给 `findElement` 函数,并打印函数的返回值。
希望这能解决您的问题。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)