c语言用指针实现将一个数组内容复制到另一个数组中并去重的程序
时间: 2025-01-06 14:48:30 浏览: 43
以下是一个使用C语言指针实现的程序,可以将一个数组的内容复制到另一个数组中并去重:
```c
#include <stdio.h>
void copyAndRemoveDuplicates(int *source, int *destination, int sourceSize, int *destinationSize) {
int *ptr1, *ptr2, *ptr3;
int found;
*destinationSize = 0; // 初始化目标数组大小
for (ptr1 = source; ptr1 < source + sourceSize; ptr1++) {
// 检查当前元素是否已经在目标数组中
found = 0;
for (ptr2 = destination; ptr2 < destination + *destinationSize; ptr2++) {
if (*ptr1 == *ptr2) {
found = 1;
break;
}
}
// 如果没有找到重复,则添加到目标数组
if (!found) {
*destination = *ptr1;
destination++;
(*destinationSize)++;
}
}
}
int main() {
int source[] = {1, 2, 2, 3, 4, 4, 5};
int sourceSize = sizeof(source) / sizeof(source[0]);
int destination[sourceSize];
int destinationSize;
copyAndRemoveDuplicates(source, destination, sourceSize, &destinationSize);
printf("原数组: ");
for (int i = 0; i < sourceSize; i++) {
printf("%d ", *(source + i));
}
printf("\n去重后的数组: ");
for (int i = 0; i < destinationSize; i++) {
printf("%d ", *(destination + i));
}
printf("\n");
return 0;
}
```
这个程序的工作原理如下:
1. `copyAndRemoveDuplicates` 函数接受源数组指针、目的数组指针、源数组大小和目的数组大小作为参数。
2. 使用两个指针 `ptr1` 和 `ptr2` 遍历源数组和目的数组。
3. 对于源数组中的每个元素,检查它是否已经存在于目的数组中。
4. 如果元素不存在于目的数组中,就将其添加到目的数组中。
5. 更新目的数组的大小。
6. 在 `main` 函数中,我们定义了一个源数组和足够大的目的数组。
7. 调用 `copyAndRemoveDuplicates` 函数,并传递必要的参数。
8. 最后,打印原数组和去重后的数组。
这个程序使用了指针运算来遍历数组,并直接操作数组元素。通过这种方式,我们实现了数组内容的复制和去重操作。
阅读全文
相关推荐


















