C 将数组指针传递给对数字进行排序的函数
我是C新手,不知道如何将数组指针传递给函数。该函数应按升序对用户输入的数字进行排序。我想我错过了一些重要的功能 我可以输入用户值,但这是我所能做到的,没有错误C 将数组指针传递给对数字进行排序的函数,c,arrays,function,pointers,C,Arrays,Function,Pointers,我是C新手,不知道如何将数组指针传递给函数。该函数应按升序对用户输入的数字进行排序。我想我错过了一些重要的功能 我可以输入用户值,但这是我所能做到的,没有错误 #include <stdio.h> int sort(int *p, int i); //function declaration int main() { int numbers[10]; // ten element array int i; printf("Please enter ten i
#include <stdio.h>
int sort(int *p, int i); //function declaration
int main()
{
int numbers[10]; // ten element array
int i;
printf("Please enter ten integer values:\n");
for(i=0; i<10; i++)
scanf("%d", (&numbers[i]));
int *p= &numbers; //a pointer that points to the first element of number
sort(int *p, int i); //function
}
//function sorts in ascending order
int sort (int *p, int i) //function definition
{
for (i=0; i<10; i++) //loop through entire array
{
printf("%d\n", *p);
}
return 0;
}
#包括
int排序(int*p,int i)//函数声明
int main()
{
整数[10];//十元素数组
int i;
printf(“请输入十个整数值:\n”);
对于(i=0;i你应该写
int *p= numbers;//a pointer that points to the first element of number
sort(p, i); //function
传递给函数的数组隐式转换为指向其第一个元素的指针
此外,函数应该如下所示
//function sorts in ascending order
int sort (int *p, int n) //function definition
{
for ( int i = 0; i < n; i++) //loop through entire array
{
printf("%d\n", *p++);
// or
//printf("%d\n", p[i]);
}
return 0;
}
//函数按升序排序
int-sort(int*p,int-n)//函数定义
{
for(int i=0;i
指针是一个变量,它包含内存中的地址
另一个变量。与(&)
运算符表示
记忆
int*p=&numbers;
此行将保存数组的第一个地址
元素。要打印数组中的每个元素,必须递增
指针printf(“%d\n”,*p++);
调用函数时
不需要声明它的参数数据类型
*p、 int i);
这是调用函数的错误方法。直接调用它们,就像这样:sort(p,i);
在您的例子中
#包括
int-sort(int*p,inti);//函数声明
int main()
{
整数[10];//十元素数组
int i;
printf(“请输入十个整数值:\n”);
对于(i=0;我认为每个人都是错误的,忽略了scanf()的返回值。
。您是否编写scanf(const char*%d,int*&numbers[i]);
调用scanf
?不。就像您不编写sort(int*p,int i);
调用sort
。@immibis试图说的是调用函数sort()第12行的
是错误的。它不应该重新声明变量的类型,直接使用它们,就像这样:sort(p,i);
还要注意,for循环内部排序将只打印数组的第一个元素10次。您应该将print语句更改为:printf(“%d\n”,p[i]);@bruceg gotcha,谢谢。那么为什么不sort呢(数字,i)
?@风向标在这种情况下,他将不知道如何正确声明指针。:)函数sort
只打印相同的数组元素,除非它执行printf(“%d\n”,*p++);
或printf(“%d\n”,p[i]”);
@Taji您必须对数组进行排序。您可以编写自己的排序函数,也可以使用标准的C函数qsort。
#include <stdio.h>
int sort(int *p, int i); //function declaration
int main()
{
int numbers[10]; // ten element array
int i;
printf("Please enter ten integer values:\n");
for(i=0; i<10; i++)
scanf("%d", (&numbers[i]));
int *p= &numbers; //a pointer that points to address of the first element of numbers array
sort(p, i); //function
}
//function sorts in ascending order
int sort (int *p, int i) //function definition
{
for (i=0; i<10; i++) //loop through entire array
{
printf("%d\n", *p++);
}
return 0;
}