Pass array to function (C) - arrays

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:
#include<stdio.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;i<length;i++) {
printf("enter number\n");
scanf("%d",&num);
arr[i]=num;
}
// just prints original
for(i=0;i<length;i++){
printf("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;j<n;j++)
{
temp=arr[0];
for (i=0;i<length-1;i++)
{
arr[i]=arr[i+1];
}
arr[length-1]=temp;
printf("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

In C you need to declare the function before "main" function, or do the declaration and definition both above the main function. Also do share your error message, for help.
Also, in C language you can't really create dynamic arrays like that( i.e. taking an integer value and then defining the size of array using it "int array[integer] " is wrong of doing it, if the value of integer is being given during runtime)
Read http://www.mathcs.emory.edu/~cheung/Courses/255/Syllabus/2-C-adv-data/dyn-array.html , or any other tutorial about dynamic arrays in C and how to use malloc and calloc.

According to me the problem is in your last print statement in rotate method which is inside the loop.
you must loop through the whole array again to print the rotated array.
like this.
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;j<n;j++)
{
temp=arr[0];
for (i=0;i<length-1;i++)
{
arr[i]=arr[i+1];
}
arr[length-1]=temp;
}
for(i=0;i<length;i++){
printf("original arr[%d]=%d\n",i,arr[i]);
}
}
this will work.
And also, Always define functions at the top in c.

Related

Problem in C : How to properly call function inside main

So there is this project in Data Structures that i have to deal with this semester and it requires that i have to code in C . The problem is that i am a little bit rusty in C and i am dealing with basic problems. One of the problems is that i have to write a simple program in C that implements BubbleSort . The BubbleSort algorithm has to be a seperate function and call it in the main program . Here is my effort . The problem is that it doesnt type the sorted array . I hope you can help me .
THE CODE :
int calculateRand()
{
int num;
num = (rand())%(UPPER-LOWER+1)+LOWER;
return num;
}
void swap(int *xp, int *yp)
{
int temp=*xp;
*xp=*yp;
*yp=temp;
}
void BubbleSort(int S[], int n)
{
int up=n;
int i,j;
while(up>1)
{
j=0;
for(i=1; i<up-1; i++)
{
if(S[i]>S[i+1])
{
swap(&S[i], &S[i+1]);
j++;
}
}
}
for(i=0; i<n; i++)
{
printf("%d\n", S[i]);
}
}
int main()
{
int n,i;
printf("Parakalw dwste mia timh sto n: \n");
scanf("%d", &n);
int S[sizeof(n)];
printf("O mi taxinomimenos pinakas einai o exis \n");
for(i=0; i<n-1; i++)
{
S[i]=calculateRand();
printf("%d\n", S[i]);
}
printf("O pinakas meta thn taxinomisi einai \n");
BubbleSort(S[sizeof(n)], n);
return 0;
}
So if we start from the top there is a problem in the calculateRand() function as you do not declare the UPPER and LOWER variables or pass them as parameters to function.
Swap function is ok.
In the BubbleSort() function you need to decrease the up variable value after the for loop.
while(up>1)
{
for(i=1; i<up-1; i++)
{
if(S[i]>S[i+1])
{
swap(&S[i], &S[i+1]);
j++;
}
}
up--;
}
Also at this point you should start iterating from 0 instead of 1 since arrays start from index 0. So for(i=0; i<up-1; i++) is the correct way to go.
Lastly in the main() function when you're declaring the array variable S you shouldn't pass the sizeof(n) since n is an integer and size of an integer is 4. Instead you want to use n as it is int S[n];
For loop to populate the array should go up to n not n-1 if you want to fill all elements of the array. However if you change this you'll need to make the similar change in the BubbleSort() function.
And finally in the BubbleSort() function call you are passing the last element of the array which is an integer whereas function expects you to pass an array. It should look like this BubbleSort(S, n); instead.
sizeof(n) has nothing to do with the value of the variable n. It's the the size of the variable n, i.e. mostly 4 bytes for the modern architectures.
Modern variants of C permit variable size arrays thus
int S[n];
would have been legit. Otherwise
int *S = (int *)malloc(n*sizeof(int));
will help.
When you call BubbleSort , your argument should be S not S[sizeof(n)];

C Searching A Value In Manually Filled Array

I'm trying to write a program which includes an array that filled by user and find a value in it which specified by user then print if it found and count of that number in array.But it works only for first element of array.My code is below:
`void searchh(int arr[],int search,int number,int counter);
int main()
{
int number,search,i;
int counter=0;
printf("How many numbers will you enter?");
scanf("%d",&number);
int array[number];
for(i=0;i<number;i++){
printf("Please enter the %d. element of the array:",i+1);
scanf("%d",&array[i]);
}
printf("Please enter the number that you're looking for:");
scanf("%d",&search);
searchh(array,search,number,counter);
return 0;
}
void searchh(int arr[],int search,int number,int counter){
int i,c;
int key=search;
int num=number;
counter=0;
int arrsize=(int)(sizeof(arr)/sizeof(int));
int arrayent[(int)(sizeof(num)/sizeof(int))];
for(i=0;i<arrsize;i++)
{
if(arr[i]==key)
{
arrayent[counter]=i;
counter++;
}
}
printf("The number that you're looking for which is %d is found %d times.\nLocations:",key,counter);
if(counter>0){
for(c=0;c<sizeof(arrayent)/sizeof(int);c++){
printf("%d\n",arrayent[c]);
}
}
else
printf("Number doesn't exist!!");
}`
And Outputs:
Thanks for your helps.
int arrsize=(int)(sizeof(arr)/sizeof(int));
This already doesn't do what you think it does. sizeof(arr) - could be 4 if size of pointer is 4 bytes. In other words you can't check array size like that inside function, arr decays to pointer of first element of array. Hence sizeof(arr) will return size of pointer which could be 4 or 8. You need to pass the number of elements of the array to the function as parameter - which is number in your case.
This:
int arrayent[(int)(sizeof(num)/sizeof(int))];
is also strange. num is int. sizeof(num) and sizeof(int) will be same - and division will give you 1.
IMO these two lines
int arrsize=(int)(sizeof(arr)/sizeof(int));
int arrayent[(int)(sizeof(num)/sizeof(int))];
should just go as
int arrsize = number;
int arrayent[number];
PS. Also try to use a debugger to help you with some kind of issues.

Passing arrays into functions, file.exe stopped working

I am a complete beginner in C and I am practicing passing arrays into functions. I wrote a program to take a two dimensional array as input and find sum of the individual columns.
And when I compiled the program I got no errors, but once I run it, I get a dialogue box saying "untitled5.exe stopped working" where untitled5 is the file name.
I got this error quite a few times. I have used both dev c++ and codeblocks to compile my program, so what is the reason for this? Is this a problem with my code or with my compiler or with my laptop?
#include<stdio.h>
void summation (int arr[][5], int size);
int main()
{
int n,arr[n][5],sum,i,j;
printf("enter the number of rows");
scanf("%d",&n);
for (i=0;i<n;i++)
{
for (j=0;j<5;j++)
{
printf("%d,%d th element is",i,j);
scanf("%d",&arr[i][j]);
}
}
summation (arr,5);
return 0;
}
void summation (int arr[][5], int size)
{
int i,j,s=0;
for(j=0;j<5;j++)
{
for (i=0;i<5;i++)
{
s=s+arr[i][j];
}
printf("%d",s);
}
}
In main() you are using i to index the first dimension of the array. In summation() you are using i to index the second dimension of the array. I think that you are going beyond the end of the first dimension inside summation() when main() does not fill up that much of the array (e.g., when you enter 2 for the number of rows).
I think you want
summation (arr,5);
And, inside summation():
for (i=0;i<size;i++)
{
s=s+arr[i][j];
}
#include<stdio.h>
void summation (int arr[][5], int size, int rows);
int main()
{
int n, sum, i, j;
printf("enter the number of rows");
scanf("%d",&n);
int arr[n][5];
for (i=0;i<n;i++)
{
for (j=0;j<5;j++)
{
printf("%d,%d th element is",i,j);
scanf("%d",&arr[i][j]);
}
}
summation (arr, 5, n);
return 0;
}
void summation (int arr[][5], int size, int rows)
{
int i,j,s=0;
for(i=0;i<rows;j++)
{
for (j=0;i<size;i++)
{
s=s+arr[i][j];
}
}
printf("%d",s);
}
So first off I moved your array declaration to after you have initialized n and made it equal to something.
Then your next problem was you were probably going out of bounds in your summation function. You always have 5 columns in your 2darray, but you can have a different amount of rows. Pass the amount of rows, n, into the function summation to make sure you don't go out of bounds.

Trying to pass an array to a function in c

I have been asked to write a lottery program in c++ not sure if i am using function correctly please help
//function prototypes
int myNumbers();
void displayNums();
#include <stdio.h>
#define NUMS 6
#define WIN 7
// function myNumbers takes input from user
int myNumbers(int numbers[]) //implememt function
{
int i;
int numbers;
int input[NUMS];
printf ("Please enter your lucky numbers\n");
for (i=0;i<NUMS;i++)//loop through array to take input
{
scanf("%d",&input[i]);
}//end for loop
return (numbers);
}//end function myNumbers
Each of your functions declares a new array, rather than using the array passed to it as an argument.
void displayNums(int print[])
{
int i;
int output;
int numbers[NUMS];
output = myNumbers(numbers);
printf("Your numbers are %d \n", output);
}
Note that nowhere is the print argument used, and you're using int numbers[NUMS] instead. Remove that declaration and use print. (Also please consider naming your argument something other than print; this name is confusing and does not accurately describe what the variable stores.)
you are not using arrays properly to communicate the numbers, see the function
int myNumbers(int userPick[]) //implememt function
{
int i;
int numbers;
int input[NUMS];
printf ("Please enter your lucky numbers\n");
for (i=0;i<NUMS;i++)//loop through array to take input
{
scanf("%d",&input[i]);
}//end for loop
numbers = *(input+i);
return (numbers);
}//end function myNumbers
it reads the number to a local array and returns *(input+i) which will be a random number since your read array is from input+0 to input+i-1. you should pass array or pointer to global array.
Even in case of display() function you are passing one array and using some other array inside display() function.
you should use a common array to communicate values. you can create a array in global scope and use it in all functions or create a array in main() and pass pointer to it to other functions and use the same array in other functions. learn how to pass arrays between functions and use arrays
Your functions looks erroneous:
int myNumbers(int userPick[]) // 1. userPick is not used anywhere
{
int i;
int numbers; // 2. initialize this variable to 1 first
int input[NUMS];
printf ("Please enter your lucky numbers\n");
for (i=0;i<NUMS;i++)
{
scanf("%d",&input[i]);
}//end for loop
numbers = *(input+i); // 3. is this suppose to be inside the loop ?
return (numbers);
}//end function myNumbers
And in
void displayNums(int print[])//implement function
{
int i;
int output;
int numbers[NUMS];
output = myNumbers(numbers);
printf("Your numbers are %d \n",output);
}//end function displayNums
You don't use print but create a new array numbers
Most of your code is erroneous. It won't compile. Here's some sample code. Work with it to implement the rest
#include <stdio.h>
#define NUMS 6
void displayNums(int nums[])
{
int i;
printf("Your numbers are:\n");
for(i = 0; i < NUMS; i++)
printf("%d ", nums[i]);
printf("\n");
}
void myNumbers(int nums[])
{
printf("Please Enter your lucky numbers\n");
int i;
for(i = 0; i < NUMS; i++)
scanf("%d", &nums[i]);
}
int main()
{
int numbers[6];
myNumbers(numbers);
displaynums(numbers);
//do the rest of the stuff here
return 0;
}
Going through a C tutorial might be helpful? Check out http://c.learncodethehardway.org/book/ for a nice intro to the language.

How to pass multi-dimensional array to function?

I am trying to pass a 2D array of variable size to a function to print it.but the code doesn't show the exact result of sum.
this is the code:
#include <stdio.h>
#define ROW 5
#define COLL 5
void print_arr(int a[][COLL],int m,int n){
int i,j,sum;
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("a[%d][%d]=%d\n",i,j,a[i][j]);
}
}
}
int sum_arr(int a[][COLL],int m,int n){
int i,j,sum;
for(i=0;i<m;i++){
for(j=0;j<n;j++){
sum+=a[i][j];
}
}
return sum;
}
int main (void){
int a[ROW][COLL];
int i,j,m,n;
int sum;
printf("enter rows:");scanf("%d",&m);
printf("enter coll:");scanf("%d",&n);
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("a[%d][%d]=",i,j);scanf("%d",&a[i][j]);
}
}
print_arr(a,m,n);
printf("\n");
sum=sum_arr(a,m,n);
printf("sum=%d\n",sum);
return 0;
}
this is the result of the code
enter rows:2
enter coll:3
a[0][0]=5
a[0][1]=8
a[0][2]=4
a[1][0]=7
a[1][1]=9
a[1][2]=6
a[0][0]=5
a[0][1]=8
a[0][2]=4
a[1][0]=7
a[1][1]=9
a[1][2]=6
sum=-1217388517
please tell me what's wrong with the code....
You should pass the exact size of the second dimension of the array to the function, not COLL. change it to m (or n, whatever)
It passes the number 5 to the function while the number should be 3 :) How ever, this is not the main reason that you're code is not working, just a suggestion.
Initialize the variable sum. It will make your code work. e.g. sum = 0;
If you don't initialize it, you won't get any compile errors, but it points to a location of memory and reads thing been there before (not a valid amount) and uses it as the initial amount of that for sum.
So your array is being added to a non-valid amount, that's why your code doesn't work.
There is no technical problem with passing, but in sum_arr,
your variable sum does not start at 0 (but some strange value).
You have to initialize sum to zero in sum_arr function.

Resources