Pass array to function (C)

Course Queries Syllabus Queries 3 years ago

8.55K 1 0 0 0

User submissions are the sole responsibility of contributors, with TuteeHUB disclaiming liability for accuracy, copyrights, or consequences of use; content is for informational purposes only and not professional advice.

Answers (1)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 3 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 de">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;id",&num);
    arr[i]=num;
 }
     // just prints original
    for(i=0;id]=%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;jd 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
0 views
0 shares

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.

Similar Forum