设有整型数组a[5]={1,3,5,7,9},b[6] = { 1,3,5,6,7,9},求a和b的交集放到数组c中。例如a和b的交集c[5]={1,3,5,7,9}。要求用指针方式实现。 c ➕➕
时间: 2023-11-19 15:12:53 浏览: 64
好的,我可以帮您解决这个问题。以下是代码:
```c
#include <stdio.h>
#define MAX_LEN 5
int main() {
int a[MAX_LEN] = {1, 3, 5, 7, 9};
int b[6] = {1, 3, 5, 6, 7, 9};
int c[MAX_LEN];
int *p1 = a, *p2 = b, *p3 = c;
while (p1 < a + MAX_LEN && p2 < b + 6) { // 依次比较a和b数组
if (*p1 < *p2) {
p1++;
} else if (*p1 > *p2) {
p2++;
} else {
*p3 = *p1;
p1++;
p2++;
p3++;
}
}
printf("交集为:");
for (int i = 0; i < p3 - c; i++) {
printf("%d ", *(c + i));
}
printf("\n");
return 0;
}
```
我们定义了两个整型数组a和b,以及一个空数组c。我们使用指针方式实现数组的遍历和比较,从而得到a和b的交集,并将结果存放到数组c中。最后,我们遍历数组c,输出交集。
相关问题
用c语言设有整型数组 a[5],b[5]和c[10],分别向a、b数组输入 5个数据,然后将a和b合并到数组c中。
您好!感谢您使用ChitGPT进行对话。
针对您的问题,可以采用如下的代码实现:
```c
#include <stdio.h>
int main()
{
int a[5], b[5], c[10];
int i, j;
// 向数组a输入5个整数
printf("请向数组a输入5个整数:\n");
for(i = 0; i < 5; i++)
{
scanf("%d", &a[i]);
}
// 向数组b输入5个整数
printf("请向数组b输入5个整数:\n");
for(i = 0; i < 5; i++)
{
scanf("%d", &b[i]);
}
// 将数组a和b合并到数组c中
for(i = 0; i < 5; i++)
{
c[i] = a[i];
}
for(j = 0; j < 5; j++)
{
c[i + j] = b[j];
}
// 输出数组c的元素
printf("数组c的元素为:");
for(i = 0; i < 10; i++)
{
printf("%d ", c[i]);
}
printf("\n");
return 0;
}
```
希望这个代码能够帮助您解决问题。如果您还有其他的问题,请随时问我。
用c语言设有整型数组 a[5],b[5]和c[10],分别向a、b数组输入 5个数据,然后将a和b合并到数组c中并排序。
好的,我理解了你的问题。以下是用C语言实现的代码,可以实现将两个整型数组a和b合并到数组c中,并进行排序。
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10
void merge_sort(int *arr, int left, int right) {
if (left >= right) {
return;
}
int mid = left + (right - left) / 2;
merge_sort(arr, left, mid);
merge_sort(arr, mid + 1, right);
int i = left, j = mid + 1, k = 0;
int *temp = (int *)malloc(sizeof(int) * (right - left + 1));
while (i <= mid && j <= right) {
if (arr[i] < arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
}
}
while (i <= mid) {
temp[k++] = arr[i++];
}
while (j <= right) {
temp[k++] = arr[j++];
}
k--;
while (k >= 0) {
arr[left + k] = temp[k];
k--;
}
free(temp);
}
void merge_arrays(int *a, int *b, int *c) {
int i, j;
for (i = 0; i < 5; i++) {
c[i] = a[i];
}
for (j = 0; j < 5; j++) {
c[i + j] = b[j];
}
merge_sort(c, 0, 9);
}
int main() {
int a[5], b[5], c[MAX_SIZE];
int i;
printf("请输入数组a中的5个数据:\n");
for (i = 0; i < 5; i++) {
scanf("%d", &a[i]);
}
printf("请输入数组b中的5个数据:\n");
for (i = 0; i < 5; i++) {
scanf("%d", &b[i]);
}
merge_arrays(a, b, c);
printf("合并后的数组c为:\n");
for (i = 0; i < 10; i++) {
printf("%d ", c[i]);
}
printf("\n");
return 0;
}
```
这段代码首先定义了一个merge_sort函数,该函数用于归并排序。然后定义了一个merge_arrays函数,用于将两个数组合并到一起并进行排序,最后在main函数中调用merge_arrays函数实现合并和排序,最终输出合并后的数组c。
阅读全文
相关推荐













