gpt4 book ai didi

c - 将数组作为参数传递并交换数据 - 意外数据

转载 作者:行者123 更新时间:2023-11-30 19:43:02 27 4
gpt4 key购买 nike

当我在交换函数中传递参数时,我期望索引 a[0]a[1] 的输出。但输出分别显示来自 a[1]a[2] 的数据。

但是为什么呢?又该如何改进呢?

下面是我的代码。

#include <stdio.h>
#include <stdlib.h>

int add(int *array,int max );
void swap(int *array,int max,int *x,int *y);

int main()
{
int sum,i,j=0,a[10],max;

scanf("%d",&max);

for(i=0;i<max;i++)
{
scanf("%d",&a[i]);
}

for(i=0;i<max;i++)
{
printf(" %d ",a[i]);
}

printf("\n");

//for(i=0;i<max;i++)
{
swap(a,max,&a[0],&a[1]);
}
sum=add(a,max); // array name is same as address of array//or sum=add(&a[0],max);
printf("%d",sum);
}

int add(int *array,int max)
{
int sum=0,i=0;
while(i<max)
{
sum=sum +array[i];
i++;
}
return sum;
}

void swap(int *a,int max, int *x,int *y)
{
int i;
/* int temp=0;

temp=a[*x];
a[*x]=a[*y];
a[*y]=temp;*/
printf("\n%d %d",a[*x],a[*y]);
for(i=0;i<max;i++)
{
printf("\n %d",a[i]);
}
printf("\n");
}

最佳答案

您的问题在下面一行

printf("\n%d %d",a[*x],a[*y]);

调用 swap() 就像

swap(a,max,&a[0],&a[1]);

如果 a[0]a[1] 的值大于 10,则您访问的数组越界。请检查并纠正您的逻辑。

FWIW,

But the output is showing the data from a[1] and a[2] respectively

这是因为,很可能 a[0] 包含 1 并且 a[1] 包含 `2

关于c - 将数组作为参数传递并交换数据 - 意外数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30153684/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com