Pass array to function (C)

Course Queries Syllabus Queries 2 years ago

0 1 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Syllabus Queries related to Course Queries. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (1)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago


I've written a function to rotate an array, I've checked and it works when code is in one block I.E. everything is coded under main(), but when I divide the code so that the rotation is done under a different function I can't get it to work (it truncates instead of rotating). I'm pretty sure it's something to do with the array pointer.

sorry complete noob

please help:

#includedio.h>
void rotate(int *arr,int length);
int main()
 {
 // this code creates an array via input
 int length;
 int i;
 int num;
    printf("enter length of array\n");
    scanf("%d",&length);
 int arr[length];
 for (i=0;iprintf("enter number\n");
    scanf("%d",&num);
    arr[i]=num;
 }
     // just prints original
    for(i=0;iprintf("original arr[%d]=%d\n",i,arr[i]);

    }


 //runs rotate function

 rotate(arr,length);

 return 0;
 }

//the rotate function inputs rotation amount and uses nested for loop to 
execute
void rotate(int *arr,int length)
{
int n;
 printf("by how many do you want to rotate array?");
    scanf("%d",&n);
    int i;
    int j;
    int temp;
    for (j=0;jprintf("rotated arr[%d] = %d\n",i,arr[i]);
    }


    }

my output looks like this:

enter length of array
5
enter number
1
enter number
2
enter number
3
enter number
4
enter number
5
original arr[0]=1
original arr[1]=2
original arr[2]=3
original arr[3]=4
original arr[4]=5
by how many do you want to rotate array?
3
rotated arr[4] = 1
rotated arr[4] = 2
rotated arr[4] = 3

RUN FINISHED; exit value 0; real time: 9s; user: 0ms; system: 0ms

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.