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;
}
A pointer is a variable which contains the address in memory of
another variable. Ampersand (&) operator denotes an address in
memory.
int *p= &numbers; this line will hold the first address of the array
element. For printing every element of an array you have to increment
the pointer printf("%d\n", *p++); and when you call a function you
don't need to declare it's argument data type. In this line sort(int
*p, int i); this is a wrong way to calling a function.just call them directly, like this way: sort(p,i); in your case.
#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;
}
This sort function is just printing the value.If you want the complete code Go here
Related
this is my leetcode 1st day 1st problem called two_sum am getting an error, please help me with the mistake what I have done,
in vs code this, below code was getting no error and also no output, but in leetcode I getting an error :
Line 25: Char 5: error: conflicting types for ‘main’ [solution.c]
int main(int argc, char *argv[]) {
^~~~
where my code is only 22 lines but I was getting error in the 25th line
#include <stdio.h>
void main()
{
int n, a[10], i, j, t;
printf("enter the array size");
scanf("%d", &n);
printf("enter th array values");
for (i = 0; i < n; i++)
scanf("%d", &a[I]);
printf("enter the targest sum");
scanf("%d", &t);
for (i = 0; i < n; n++)
{
for (j = i+1; j < n; n++)
{
if (a[i] + a[j] == t)
{
printf("[%d,%d]", i, j);
}
}
}
}
2nd try: I replaced with a new code in the last if statement to check in another way. so, now I got output but, not the correct one
According to the C Standard the function main without parameters shall be declared like
int main( void )
Instead of the array with the fixed number of elements
int n, a[10], i, j, t;
you could use a variable length array like for example
int n, i, j, t;
printf("enter the array size");
scanf("%d", &n);
int a[n];
Another approach is to allocated the array dynamically like
int *a = malloc( n * sizeof( int ) );
You can write either each pair of values in a new line like
printf("[%d,%d]\n", i, j);
Or after all pairs you could print the new line character like
for (i = 0; i < n; n++)
{
for (j = i+1; j < n; n++)
{
if (a[i] + a[j] == t)
{
printf("[%d,%d] ", i, j);
}
}
}
putchar( '\n' );
{ay attention to that you have a typo
scanf("%d", &a[I]);
^^^
you need to write
scanf("%d", &a[i]);
^^^
Try declaring main as int main(int argc, char * argv[]) or int main(void). void main is usually not a valid type declaration so I presume both VS Code and Leetcode do not treat your main declaration as the entry to your program.
In leetcode, you don't need to (and should not) write your own main function. Leetcode has its own main function. Also you don't need to include libraries. What you need to do is just to implement the twoSum function.
Here's Leetcode's default code definition for the two sum problem:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
}
What you need to do is write code within the twoSum() function.
// don't need to #include<stdio.h>
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
// write your code here.
}
// don't need to write main function
i'm new to programming and i'm learning about recursion, i am doing exercise 4 from this page
https://www.w3resource.com/c-programming-exercises/recursion/index.php, i am trying to print the elements of the array once the value of "i" in the recursive function gets to the value of "n", however once i run the program it prints garbage values i think.my question is why does it do that? why doesn't it print the values of the array?
#include <stdio.h>
#include <stdlib.h>
void printr(int n,int i);
int main (void)
{
printf("NUMBER OF ELEMENTS:\n");
int n;
scanf("%i",&n);
printr(n,0);
}
void printr(int n,int i)
{
int arr[n];
if (i == n)
{
for (int j = 0; j < n; j++)
{
printf("%d",arr[j]);
return;
}
}
printf("element %d :\n",i+1);
int e;
//scan for input
scanf("%d",&e);
//populate array
arr[i]=e;
//do it again
printr(n,i + 1);
}
Then i solved it by passing the array defined in the mein function asan argument in the printr function
it worked but i don't understand why my first attemp didn't?
#include <stdio.h>
#include <stdlib.h>
void printr(int arr[],int n,int i);
int main (void)
{
printf("NUMBER OF ELEMENTS:\n");
int n;
scanf("%i",&n);
int arr[n];
printr(arr,n,0);
}
void printr(int arr[],int n,int i)
{
if (i == n)
{
for (int j = 0; j < n;j++)
{
printf("%d ",arr[j]);
}
printf("\n");
return;
}
printf("element %d :\n",i+1);
int e;
//scan for input
scanf("%d",&e);
//populate array
arr[i] = e;
//do it again
printr(arr,n,i + 1);
}
Thank you!
Because basic C: each invocation of printr has its own arr on the stack, initially uninitialized. And you print it without initializing it first.
When you print out the value, it isn't initialized first. When you create the variable to be printed, its pointing to a place in memory. This memory was probably freed by another program (so its up for grabs). As such, it contains "garbage" data. The way to deal with this is to initialize your values.
In order to avoid stuff like this in the future, get in the habit of setting your pointers to NULL when you don't initialize them so that your programs segfaults when your trying to read an uninitialized value.
Say I have an array of n characters.
I want to pass the amount, and a pointer to the array to a function, to check for the biggest value in the array. However, I'm unsure how to access the values from the pointer.
#include <stdio.h>
int max(int *numbers, int size) {
int temp = size;
for (int i=0;i<temp;i++) {
/*How do i access the array values?*/
}
return 0;
}
int main(void) {
int amount;
int Array[amount];
int *ptr;
printf("Enter size of array:");
scanf("%d",&amount);
ptr = &Array[amount];
for(int i=0;i<amount;i++) {
scanf("%d",&Array[i]);
}
printf("Number 2 in array: %d",Array[1]);
printf("\n calling function \n");
max(ptr,amount);
return 0;
}
Two problems -- you don't set amount before using it to create Array so you get an undefined-size array, and Array[amount] is past the end of the array. What you want is something more like:
int amount;
int *ptr;
printf("Enter size of array:");
scanf("%d",&amount);
int Array[amount];
ptr = Array;
and having ptr as a separate variable is not terribly useful -- you can just call max(Array, amount)
I've been trying to write a void function called printReverse that takes a double array named d and an int called n as arguments, where n is the number of elements in d. I want printReverse to print the n array values in reverse order. This is what I have so far, but I'm having difficulty declaring arguments.
#include <stdio.h>
int n
double d[n]
void printReverse(d[], double newArray){
int i;
int j;
for (i=0; j=n-1; i<n; i++; j--;){
newArray[j]=d[i];
}
printf("%lf\n",newArray);
}
Any help in what I'm doing wrong would be very much appreciated.
REVISION: Would this code work
void printReverse(double [] d, int n){
int i;
for(i=n-1;i>=0;i--){
printf("%f\n",d[i]);
}
If you want both print and store the array in reverse order you could do something like this:
#include <stdio.h>
void printReverse(double *d, double *newArray, int n){
int i;
int j;
for (i=0, j=n-1; i<n; i++, j--){
newArray[i]=d[j];
printf("%lf\n",newArray[i]);
}
}
int main(){
int n = 4;
double array[] = {1, 2, 3, 4};
double newArr[n];
printReverse(array,newArr,n);
}
//take pointer to array, and size of array as parameters
void printReverse(double* arr,int size){
for(int i =0;i<size;i++){
printf("%f\n",arr[(size-1)-i]);
//(size-1)-i will compute the proper index of the array to read backwards.
//remeber arrays are 0 based meaning that the first member in the array is index 0
}
}
this should do the trick.
EDIT: or if you are trying to reverse the array into a new array and then print...
void printReverse(double* arr,double* arr2,int size){
for(int i =0;i<size;i++){
arr2[(size-1)-i]=arr[i];
}
for (int i=0; i<size; i++) {
printf("%f\n",arr2[i]);
}
}
you will need to have the arrays in the code that calls this function.
so...
double arr[5] = {1,2,3,4,5};
double arr2[5];
printReverse(arr,arr2, 5);
How do i make it so that i can use #define variables in my functions? I need to create a program that calls upon functions with this code. Basically my functions at the bottom can change but my main function cannot change from this kind of format, so however i write my functions i have to pass the variable a and variable SIZE through the functions. But current it seems that SIZE is not actually recognized as an int variable.
#include <stdio.h>
#define SIZE 9
int i, position, tmp;
void readArray(int a[]);
void printArray(int a[]);
void sortArray(int a[]);
int main(void)
{
int a[SIZE];
readArray(a);
printArray(a);
sortArray(a);
printf("After sorting:\n");
printArray(a);
return 0;
}
//Functions//
void readArray(int a[]){
printf("Please enter %d integers: ", SIZE);
for (i=0; i<SIZE; i++) {
scanf("%d", &a[i]);
}
}
void printArray(int a[]){
for (i=0;i<SIZE;i++) {
printf("a[%d] = %3d\n", i, a[i]);
}
}
void sortArray(int a[]){
for (i=0; i<SIZE; i++) {
// In each iteration, the i-th largest number becomes the i-th array element.
// Find the largest number in the unsorted portion of the array and
// swap it with the number in the i-th place.
for (position=i; position<SIZE; position++) {
if (a[i] < a[position]) {
tmp = a[i];
a[i] = a[position];
a[position] = tmp;
}
}
}
}
Writing
#define SIZE 9
will tell the preprocessor to replace each appearance of SIZE with 9.
meaning, the following line -
void sortArray(int a[], int SIZE)
will be replaced with -
void sortArray(int a[], int 9)
I assume you understand this is illegal.
You should just delete the second function parameter.
You should rename the C variables to something other than SIZE. This is already used by the preprocessor. Also, watch out because you've written Int instead of int.