I want to return the average of the two dimensional array with a different array using a function, the program runs fine, but it returns a big negative number, how do i return the array or apply pointers to my function? where do i add the pointer to make it work?
I encounter this:
warning: passing argument 1 of 'returnAvg' makes pointer from integer without a cast [enabled by default]|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void returnAvg(int allTest[2][2],int students,int test);
int main ()
{
int students = 2, test = 2, i,j;
int allTest[students][test];
for(i=0;i<students;i++){
for(j=0;j<test;j++){
printf("Student [%d] test [%d] score was> ",i+1,j+1);
scanf("%d",&allTest[i][j]);
}
}
returnAvg(allTest[2][2],students,test);
return 0;
}
void returnAvg(int allTest[2][2],int students,int test){
int i,j;
int avg[students];
for(i=0;i<students;i++){
int sum = 0;
for(j=0;j<test;j++){
sum += (allTest[i][j]);
}
avg[i] = sum/test;
}
printf("the average is %d, %d", avg[0],avg[1]);
return;
}
Here a quick update of your code, allTest arg should be reworked too
The way you used to pass the array to the function returnAvg is wrong! The simplest way I see it's to pass the array as a pointer. This because this kind of array is a chunk or contiguous memory areas!
I think the array and the vector may be allocated using a different way! Maybe using C++ new or C malloc; but this will become your next step!
The way to retrieve the vector containing the avg will be discussed below!
I've compiled your code under a 64 bit system adding this code into your main:
The output shall be something like this:
This indicates what I said! All elements are contiguous!
We understand that there's a "base" pointer that points the first element. In the output is 0x7fff0cd89e60 (that is the pointer to allStudent[0][0]).
The relationship between this pointer and all pointers of the element of the array is:
Stating the pointer arithmetic we can modify your function as:
You may call this function in your main as:
Now we may see how to pass the avg array to the main!
Here the code where you may also modify the number of students and tests results!
is wrong since
allTest[2][2]
evaluates to anint
and the function expects an arrayint [2][2]
.You need to use:
Your code is good except:
should be
You don't have to give size of
attTest
here, because you are not defining it here, just a parameter providing to the function. You may see you working code here.