[英]Changing the values in a number array in C
I want to make a program that uses a function I created where it swaps all the elements of an array X (that has the length of N) with some number K, only if that element is greater than K. Where am I going wrong here? 我想制作一个使用我创建的函数的程序,该函数将数组X(长度为N)的所有元素交换为某个数字K(仅当该元素大于K时)。我在这里哪里出错了? ?
#include <stdio.h>
#include <stdlib.h>
int swap_K(int *, int);
int main()
{
int N,i,K;
printf("Enter N: ");
scanf("%d",&N);
printf("Enter K: ");
scanf("%d",&K);
int X[N];
for (i=1; i<=sizeof(X)/sizeof(int); i++){
printf("Enter %d. element: ",i);
scanf("%d",&X[i]);
}
swap_K(X,K);
for (i=1; i<=sizeof(X)/sizeof(int); i++){
printf("%d",X[i]);
}
}
int swap_K(int *X, int K)
{
int i;
for (i=1; i<=sizeof(X)/sizeof(int); i++){
if (X[i]>K)
X[i]=K;
}
return X;
}
In swap_K(int *X, int K)
, sizeof(X)
is sizeof(int *)
, not the size of the array. 在
swap_K(int *X, int K)
, sizeof(X)
是sizeof(int *)
,而不是数组的大小。
In C, a pointer is not really the same as an array. 在C语言中,指针与数组并不完全相同。
To fix it, use N
instead of sizeof(X)/sizeof(int)
everywhere, esp. 要修复此问题,请在所有地方使用
N
代替sizeof(X)/sizeof(int)
,尤其是。 inside swap_K()
. 在
swap_K()
内部。
1) Arrays start with index 0
. 1)数组从索引
0
开始。
2) In your main
function you don't need to use sizeof(X)/sizeof(int)
in for
loop as you already know it is equal to N
. 2)在您的
main
函数中,您无需在for
循环中使用sizeof(X)/sizeof(int)
,因为您已经知道它等于N
3) When you pass the array to the function, you are sending the base address of the array which decays into pointer, so in swap_K
function, sizeof(X)
will return sizeof(int)
which is 4
(generally). 3)当您将数组传递给函数时,您要发送的数组的基地址将衰减为指针,因此在
swap_K
函数中, sizeof(X)
将返回sizeof(int)
,其值为4
(通常)。
To overcome this you should send the size of your array from main
function. 为了克服这个问题,您应该从
main
函数发送数组的大小。 For example: swap_K(X,K,N);
例如:
swap_K(X,K,N);
4) You don't need to return X
from swap_K
as you are sending the base address of X
from main
function. 4)当您从
main
函数发送X
的基地址时,不需要从swap_K
返回X
For example: 例如:
#include <stdio.h>
#include <stdlib.h>
int swap_K(int *, int, int);
int main()
{
int N,i,K;
printf("Enter N: ");
scanf("%d",&N);
printf("Enter K: ");
scanf("%d",&K);
int X[N];
for (i=0; i<N; i++)
{
printf("Enter %d. element: ",i);
scanf("%d",&X[i]);
}
swap_K(X,K,N);
for (i=0; i<N; i++)
{
printf("%d",X[i]);
}
}
int swap_K(int *X, int K,int N)
{
int i;
for (i=0; i<N; i++)
{
if (X[i]>K)
X[i]=K;
}
//return X; //This is not required
}
Your loop is incorrect 您的循环不正确
for (i=1; i<=sizeof(X)/sizeof(int); i++)
It should be 它应该是
for (i=0; i<N; i++)
There are several problems with the code posted: 发布的代码存在几个问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.