I'm new to C and cannot figure out how to pass a pointer of an array to a function. The function should sort user input numbers in ascending order. I think I've missed something crucial in the function.
I'm able to input the user values but that's as far as I've been able to get without errors.
#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;
}
You should write
int *p= numbers;//a pointer that points to the first element of number
sort(p, i); //function
An array passed to a function is converted implicitly to pointer to its first element.
Also the function should look like
//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;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments