本题要求实现一个函数,可从一个结构体数组data域中查找一个给定的数据元素x,查找成功,返回该元素所在位置的指针;否则,返回NULL。
时间: 2024-05-10 21:16:58 浏览: 11
以下是一个可能的实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data;
} Element;
Element* search(Element data[], int n, int x) {
int i;
for (i = 0; i < n; i++) {
if (data[i].data == x) {
return &data[i];
}
}
return NULL;
}
int main() {
Element data[MAX_SIZE];
int i, n, x;
Element* result;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter the elements: ");
for (i = 0; i < n; i++) {
scanf("%d", &data[i].data);
}
printf("Enter the element to search for: ");
scanf("%d", &x);
result = search(data, n, x);
if (result == NULL) {
printf("Element not found\n");
} else {
printf("Element found at index %ld\n", result - data);
}
return 0;
}
```
该函数接受三个参数,分别是结构体数组data、数组长度n和要查找的元素x。在函数内部,使用一个循环遍历数组,查找是否存在与x相等的元素。如果找到了,返回该元素所在位置的指针,否则返回NULL。
在主函数中,先读入结构体数组和要查找的元素,然后调用search函数进行查找。如果查找成功,输出该元素所在位置的下标,否则输出“Element not found”。