Pass arrays to function - c

Apologies for this re-post as I do not know how to phrase my question as it is my first time using stack overflow. I hope someone could help me out in this quiz for my studies.
I had research on this program but I do not know if it relates to the quiz question on arraySize.
Question is below:
we pass array ai to function fillArray. What exactly is passed to the function? The answer is a single memory address, not the 10 integers! This is why we can use the function to fill the array ai with 10 numbers.
Complete the above function fillArray so that it reads arraySize number of integers from the user and fill the array with those numbers.
Write a driver program to test the function with integer arrays of different sizes.
Note the formal parameter int array[] in function fillArray can be changed to int *array. Verify this by modifying and testing your code.
My code is below:
#include <stdio.h>
#define MAX 10
int fillArray(int array[], int arraySize);
void print_intaray(int array[], int arraySize);
main()
{
int ai, exam_scores[MAX];
printf("***List of Array***\n\n");
ai = fillArray(exam_scores, MAX);
print_intaray(exam_scores, ai);
}
int fillArray(int array[], int arraySize)
{
int ai, count = 0;
printf("Type array, EOF to quit\n");
while ((count < arraySize) && (scanf("%d", &ai) !=EOF))
{
array[count] = ai;
count++;
}
return count;
}
void print_intaray(int array [], int arraySize)
{
int i;
printf("\n***Your Arrary***\n\n");
for (i = 0; i<arraySize; i++)
printf("%d\n", array[i]);
}
I'm new to programming and I hope my question could somehow be resolve.
Thanks for viewing :)

Assuming the question is "Why are int array[] and int *array equivalent in the function argument":
I'm not much of a C expert, but AFAIK arrays (in C) are largely just pointers to which you append a certain offset. Telling C you expect an int myarray[] means pretty much the same as expecting a pointer to an integer (int *array). If you increment the pointer, you can access the next element in the array. This is also known as pointer arithmetic.
The C compiler translates array syntax like foo[3] in the background to something like *(*foo+3), but you can also do that yourself by just dealing with the pointers.

Related

How to pass the user value for the size of an array into a function implemented in another code file?

I have no idea what to do. Whenever I try to insert read_num[size] it does not work. My debugger shows the value as 0. I want to take a value for the size of the array from the user. Then I want to use the value in another file.
So what I want to do is, I will do a printf to ask the user to give a value so that I can pass it as the size of the array. I did and it didn't work. Then I decided to write a direct value [36]. But I want user to insert 36.
This is what I have tried:
main.c
int main(void)
{
int numbers[ARR_SIZE] = { 0 };
int size = 36; // I am doing directly but I want to take the value from the user but it just does not work.
double mean = 0;
double stddev = 0;
read_array(size);
}
file.c
int read_array(int a[36]) //placing 36 directly, I want it to be placed by the user
{
int num_read[36]; int i = 0; // I have no clue whats i am doing. I just want to pass the value from the user.
while (i < a)
{
printf("Enter number");
scanf_s("%d", &num_read[i]);
++i;
}
}
header file
#include <stdio.h>
#include <math.h>
#define ARR_SIZE 100
int read_array(int arr[ARR_SIZE]);
double calc_mean(int arr[], int size);
double calc_stddev(int arr[], int size);
void print_array(int arr[], int size);
In you main.c file you want to decide the value of size and use that value in a call to the function read_array().
You do so by calling read_array(size);, which makes sense to me.
Sadly your shown code lacks the details of whether or not you include your header file (and others). I assume that it does.
However, if what you are doing inside main() is actually what you want to do (I assume so), then the header file and the implementation of read_array() does not match that intention.
This int read_array(int arr[ARR_SIZE]), in your header and your implementation, means
"Dear compiler, this function takes an array (or a pointer to 100 consecutive ints)."
That does not match your plan of "I will give a single int as the parameter to the function."
To match that plan, use a prototype of int read_array(int a);.
The implementation code as shown should then work.
If you want the local array to actually be of the size given by the user and arriving via the parameter a, then change
int num_read[36]; to int num_read[a];.
However, I suspect that you then intend to return the array which you filled with input from the user.
That is neither possible with a prototype of int read_array(int a); nor with one of int read_array(int arr[ARR_SIZE]);. Both mean "This function will return a single int.".
I assume you will need help with that, but you need to ask a separate question on how to return a new array from a C function - or better first search StackOverflow for a duplicate.
To pass the size of the array to the function (it does not matter if it is defined in the same or another compilation units) you need to have an additional parameter to the function. There is no other way of doing it in C language
int *doSomethingWithArray(int *array, size_t size)
{
/* ... */
}
But I want user to insert 36.
The user can only enter something using I/O functions and has no access to the C code.
int *initArray(int *array, const size_t size)
{
for(size_t index = 0; index < size; index ++)
array[index] = rand();
return array;
}
int *printArray(int *array, const size_t size)
{
for(size_t index = 0; index < size; index ++)
printf("array[%3zu] = %d\n", index, array[index]);
return array;
}
int main(void)
{
size_t array_size;
srand(time(NULL));
if(scanf("%zu", &array_size) == 1) // user enters the size of the array
{
int array[array_size];
initArray(array, array_size);
printArray(array, array_size);
}
}
https://godbolt.org/z/xjh9qGcrz

Finding the maximum of an array recursively

I am learning recursion. As an exercise I am trying to find the maximum of an array recursively.
int recursive (int *arr, int n, int largest) {
if(n==0)
return largest;
else {
if (*(arr+n)>largest) {
largest = *(arr+n);
recursive(arr, n-1, largest);
}
}
}
int main() {
int length = n-1;
int largest = v[0];
int z = recursive(arr, length, largest);
printf("\n%d", z);
}
I followed your suggestions, using pointers instead of arrays, and probably the program looks way better. But still it is not doing it's not showing the maximum correctly. I think the logic is correct.
First thing pay attention to compiler warnings, your recursive function doesn't return value when you enter the else part.
Now the second thing is please don't use things like *(arr+n) which is hard to read instead use arr[n], also while just a preference when using arrays as function arguments use int arr[] to call the function instead of int *arr (in the first version it's clear you should pass an array).
Third thing is to name your things instead of int recursive describe what the function is doing for example int maxElemRecursive
So your recursive function should be something like
int maxElemRecursive(int arr[],int n,int largest)
{
if(n==0) return largest;
if(arr[n] > largest) // No need for else because return largest; would've returned value;
{
largest = arr[n];
}
return maxElemRecursive(arr,n-1,largest); // You have to return the value of the function.
// You still pass the array with just arr.
}
In C usually you can't declare an array whose size is unknown at compile-time, hence int v[n] is dangerous code.
Depending on your compiler and the compiler's settings this could be a compile error or it could be a bug.
For such problems you need to learn about pointers and dynamic memory allocation.
Side-note: After C99 there are stuff like Variable Length Arrays but the rules are a little advanced.
Also to pass an array to a function you give the array a pointer as an argument:
int z = recursion(v, n, v[0]);
instead of:
int z = recursion(v[n], n, v[0]);

C - function (Assume that a and n are parameters where a is an array of int values and n is the length of the array.)

I'm new to programming and I don't really understand this question. Can some of you give me examples of what it means. How do I write a function where a is int values and n is the length?
I'm confused...
I'm not sure what your question is, as you haven't provided much information. However, a function in C is defined like this:
return_type function_name( parameter list ) {
body of the function
}
So, for this situation, we could say:
void arrayFunction( int a[], int n){
//do whatever you need to do with the function here
}
This may help you some.
Suppose you have an array of ints, as follows:
int arr[] = {2,3,4,5,6};
You can see that there are 5 elements inside above array arr. You can count them.
But it happens that when you pass the above arr to function, that function has no idea about how many elements arr contains. See below (incorrect) code snippet:
#include <stdio.h>
void display(int arr[]){
}
int main(void) {
int arr[] = {2,3,4,5,6};
display(arr);
return 0;
}
The function named 'display()' has no idea about how many elements arr has
Therefore you you need to pass the extra argument (the extra argument called 'n') to tell that called function about the number of elements inside arr. You need to tell this separately - the length of arr.
Now this becomes - as you said in your question - arr is int values and n is the length
Below is the correct code:
#include <stdio.h>
void display(int a[], int n){
//Now display knows about lenth of elemnts in array 'a'
// Length is 5 in this case
}
int main(void) {
int arr[] = {2,3,4,5,6};
display(arr, 5);
return 0;
}
Now, the function named 'display()' knows the length of array of int. This is the way you write code where you specify your array and its length.
More formally, this is because while passing array, it decays to a pointer and so the need arises to pass its length also alongwith it.

Pass a 2D char array to a function in C

I'm a beginning programmer who is confused with passing a two dimensional array to a function. I think it may just be a simple syntax problem. I've looked for an answer, but nothing I've found seems to help, or is too far above my level for me to understand.
I identify the array and the function in the main function as, and after initializing it, attempt to call it:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int const ROWS = 8;
int const COLS = 8;
int main(int argc, char** argv) {
char board[ROWS][COLS];
bool canReach(char board[][], int i, int j);
//initialize array
//values of i and j given in a for loop
canReach(board, i, j);
return (EXIT_SUCCESS);
}
While writing the function outside the main function, I defined it exactly the same as I did in the main function.
bool canReach(char board[][], int i, int j){
//Functions purpose
}
When I attempt to build the program, I'm given this error twice and the program does not build:
error: array has incomplete element type 'char[][]'
bool canReach(char board[][], int i, int j)
^
Please note that I'm trying to pass the entire array to the function, and not just a single value. What can I do to fix this problem? I would appreciate it if it didn't have to use pointers, as I find them quite confusing. Also, I've tried to leave out things that I thought weren't important, but I may have missed something I needed, or kept in things I didn't. Thank you for your time in helping out this starting programmer!
You can just pass arrays as function arguments with definition of their size.
bool canReach(char board[ROWS][COLS], int i, int j);
When the size is unknown, pointers are the way.
bool canReach(char* board, int i, int j);
You should know, that arrays != pointers but pointers can storage the address of an array.
Here is a demonstrative program
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
bool canReach( int n, int m, char board[][m] )
{
for ( int i = 0; i < n; i++ )
{
for ( int j = 0; j < m; j++ )
{
board[i][j] = 0;
}
}
return printf( "Hello SaarthakSaxena" );
}
int main( void )
{
const int ROWS = 8;
const int COLS = 8;
char board[ROWS][COLS];
canReach( ROWS, COLS, board );
return EXIT_SUCCESS;
}
Its output is
Hello SaarthakSaxena
Defining a function inside another function (here: main) is not allowed in C. That is an extension of some compilers (e.g. gcc), but should not be used.
You have to specify the dimension of the array. C arrays do not have implicit size information as in HLL.
It also is not a good idea to use const variables for array dimensions in C. Instead
#define ROWS 8
#define COLS 8
Assuming i and j are the indexes of an element in the array, you can use the signature:
bool canReach(size_t rows, size_t cols, char board[rows][cols],
size_t i, size_t j);
This allows to pass arrays of (run-time) variable size to the function. If the dimensions are guaranteed fixed at run-time:
bool canReach(char board[ROWS][COLS], size_t i, size_t j);
But only if using the macros above. It does not work with the const variables.
Both versions tell the compiler which dimension the array has, so it can calculate the address of each element. The first dimension might be omitted, but there is nothing gained and it would imhibit optional bounds checking (C11 option). Note the 1D-case char ca[] is just a special version of this general requirement you can always omit the left(/outer)most dimension.
Note I changed the types to the (unsigned) size_t as that is the appropriate type for array-indexing and will generate a conversion warning if properly enabled (strongly recommended). However, you can use int, but have to ensure no value becomes negative.
Hint: If you intend to store non-character integers in the array or do arithmetic on the elements, you should specify the signed-ness of the char types. char as such can be either unsigned or signed, depending on implementation. So use unsigned char or signed char, depending what you want.

Passing array to function, to multiply every value of the array by 10

This program is to multiply every value of array by 10 using a function. I am getting a lot of errors.
Can I take size in for loop?
#include<stdio.h>
mult(int arr[])
{
int i;
for(i=0;i<size;i++)
{
arr*=10;
}
return arr;
}
int main()
{
int j[];
printf("enter the all ten values to multiply by 10");
for(j=0;j<size;j++)
scanf("%d");
j[] = mult(j);
printf("%d",&j);
return 0;
}
int j[]; You're creating an array wrongly (in this context). You have to specify its size. Eg.: int j[256];
for(j=0;j<size;j++) scanf("%d"); What's size? how can you increment an array?? You're using scanf wrongly. You should do for(int s=0;s<size;s++) scanf("%d",&j[s]);.
j[] = mult(j); is wrong again. You should create another array and copy values there.
printf("%d",&j); you don't need & here, remove it. You'd better use "%d\n" to print each number on its own line.
mult(int arr[]) function declared wrongly. You must specify a type your function returns. You may need to use int *mult(...) instead and return &arr[0];
arr*=10; what're you trying to achieve with this? Completely wrong, you're multiplying the address here.
Read the docs, please! Your code doesn't make any sense, please learn C first, then try to code.
Moreover, you'll need pointers here, pay attention to them. I'd advise you to write Hello World program first to just understand the basics. Mr. Kernighan and Mr. Ritchie will help you too.
Note: I may have missed some mistakes here as there are too many of them. Please correct me if so.
Here is a complete code learn the differences and correct your code:
#include<stdio.h>
void mult(int *arr,int size)
{
int i;
for(i=0;i<size;i++)
arr[i]*=10;
}
int main()
{
int size=10;
int j[size],i;
printf("enter the all ten values to multiply by 10\n");
for(i=0;i<size;i++)
scanf("%d",j+i);
mult(j,size);
for(i=0;i<size;i++)
printf("%d ",j[i]);
printf("\n");
return 0;
}
You must tell mult() what is the size of the array, and the array you are passing will be modified in mult() so you don't need to return a value.
mult(j, size);
and your mult() function
void mult(int *arr, size_t size)
{
int i;
for(i=0;i<size;i++)
{
arr[i] *= 10;
}
}

Resources