The task is to fill an array with numbers by user input and then use our stats() function to calculate average etc. of each row of this array. The header of stats() function looks as follows:
int stats(int (*ptr)[5], int width, int height, int row_id, int* max, int* min, float *avg)
where ptr is a pointer to the matrix,width and height are its size, row_id is the index of analysed row and max, min and avg are pointers to variables storing each statistics.
When calling a function with such line:
stats(*ptr, 5,5,2, *max = NULL, *min = NULL, *avg=NULL);
the following error appears:
error: invalid type argument of unary '*' (have 'int')
I tried different approaches but there is always a mistake, how can I fix that? Thank you for any clues.
edit:
Here's the whole code:
#include <stdio.h>
int stats(int (*ptr)[5], int width, int height, int row_id, int* max, int* min, float *avg)
{
int j, vmax,vmin;
int max = &vmax;
int min = &vmin;
int i = row_id;
int m = *ptr;
for(j = 0; j<5; j++){
if(m[i][j]>max)
{
max = m[i][j] ;
j++;
else
j++;
}
}
printf("%d", max);
return 0;
}
int main(void){
int n, i, j, vmin, vmax; // vmax - value of the maximum
int min = &vmin; // min - pointer to the minimum
int max = &vmax;
float vavg;
int avg = &vavg;
int m[5][5];
for(i = 0; i<5; i++)
{
for(j = 0; j<5; j++)
{
printf("ENTER A NUMBER: ");
scanf("%d", &n);
m[i][j] = n;
}
}
int ptr = &m;
stats(*ptr, 5,5,2, *max = NULL, *min = NULL, *avg=NULL);
return 0;
}
Your code full of bugs.
For example min and max are not declared as pointers
int min = &vmin; // min - pointer to the minimum
int max = &vmax;
Also it is unclear why the variable avg has the type int and is initialized by a pointer expression of the type float *.
float vavg;
int avg = &vavg;
Or the variable ptr of the type int is initialized by the address of the two-dimensional array.
int ptr = &m;
As for the function then if the function operates only on one row then there is no any sense to pass to the function the whole two-dimensional array.
Also the return type and the returned value of the function do not make a sense.
And the function shall not output any message. It is the caller of the function that will decide output a message or not.
And also the function contains bugs where you are redeclaring its parameters like for example
int max = &vmax;
that again does not make a sense.
Using your approach the function can be declared and defined the following way
#include <assert.h>
//...
void stats( const int *a, size_t n, int *max, int *min, float *avg )
{
assert( n != 0 );
*max = a[0];
*min = a[0];
float sum = a[0];
for( size_t i = 1; i < n; i++ )
{
sum += a[i];
if ( *max < a[i] )
{
*max = a[i];
}
else if ( a[i] < *min )
{
*min = a[i];
}
}
*avg = sum / n;
}
And called like
int min = 0;
int max = 0;
float avg = 0.0f;;
//...
stats( m[2], 5, &max, &min, &avg );
printf( "max = %d\n", max );
printf( "min = %d\n", min );
printf( "average = %f\n", avg );
When you are using pointers as function parameters be carefull. If you have something like this:
int func(int *max){
}
max ,here, is a pointer which needs to hold an address. So inside this function when you need use it, you need to dereference it by using *. For example:
int func(int *max){
*max = $someAddress
}
Related
I dont know how to get the code to print out the elements that are divisable with 3 and the print out the sum of those elements , can someone help me do it , thanks for your time!
Code:
#include <stdio.h>
int sum(int arr[]){
int n = sizeof(arr) / sizeof(arr[0]);
int sum = 0;
for (int y=0;y<n;y++){
sum += arr[y];
printf("%d",sum);
}
}
int main() {
int F[5] = {1,3,5,9,8};
int s = 0;
for (int i=0;i<5;i++){
if (F[i]%3 == 0) {
int diviz[] = {F[i]};
printf("%d\n",diviz[0]);
sum(diviz);
}
}
return 0;
}
Expected Output:
3
9
12
Actual Output:
3
349
910
Idk how to solve this issue
This function declaration
int sum(int arr[]){
is adjusted by the compiler to the declaration
int sum(int *arr){
That is within the function the variable arr has the pointer type int *.
Thus the declaration with sizeof expression
int n = sizeof(arr) / sizeof(arr[0]);
is equivalent to
int n = sizeof( int * ) / sizeof( int );
and yields either 2 or 1 depending on the size of the pointer.
On the other hand, this call of the function
int diviz[] = {F[i]};
printf("%d\n",diviz[0]);
sum(diviz);
in any case does not make a great sense because instead of passing the original array you are passing an array that contains only one element. And the for loop in main is redundant.
You need explicitly to pass the number of elements in the array.
So the function can look like
long long int sum( const int arr[], size_t n, int divisor )
{
long long int sum = 0;
for ( size_t i = 0; i < n; i++ )
{
if ( arr[i] % divisor == 0 ) sum += arr[i];
}
return sum;
}
And the function can be called like
int arr[] = {1,3,5,9,8};
const size_t N = sizeof( arr ) / sizeof( *arr );
int divisor = 3;
printf( "The sum of elements divisible by %d = %lld\n", divisor, sum( arr, N, divisor ) );
The function will be more safer if to add a check whether divisor is passed equal to 0 as for example
long long int sum( const int arr[], size_t n, int divisor )
{
long long int sum = 0;
if ( divisor != 0 )
{
for ( size_t i = 0; i < n; i++ )
{
if ( arr[i] % divisor == 0 ) sum += arr[i];
}
}
return sum;
}
int main() {
int F[5] = {1,3,5,9,8};
int s = 0;
for (int i=0;i<5;i++){
if (F[i]%3 == 0) {
s = s + F[i];
printf("%d",F[i]);
}
}
printf("%d",s); //print sum total
return 0;
}
i'm not good at english.
i declare array and two pointers.
the maxPtr pointer should have array arr's maximum number adress.
and minPtr pointer should have array arr's minimum number adress.
so i declare the function and this has two double-pointer to give maxPtr and minPtr proper adress.
but whenever i run this code, the program is not fully run.
it doesn't output the result( printf("%d",*maxPtr) ,printf("%d", *minPtr, printf("Hi");
this program is run at vscode in mac.
what make it error?
#include <stdio.h>
void MaxAndMin(int* str,int** max, int** min)
{
int i;
int maxnum=0,minnum=0;
for(i=0; i<5; i++)
{
if(maxnum< str[i])
{
maxnum =str[i];
*max = &str[i];
}
if(minnum > str[i])
{
minnum = str[i];
*min = &str[i];
}
}
}
int main(void)
{
int i,len;
int* maxPtr;
int* minPtr;
int arr[5]={};
for(i=0; i<5; i++)
{
printf("%d번째 정수입력 입니다.",i+1);
scanf("%d", &arr[i]);
}
MaxAndMin(arr,&maxPtr,&minPtr);
printf("%d",*maxPtr);
printf("%d",*minPtr);
printf("Hi");
return 0;
}
the result is
> Executing task: ./test <
1번째 정수입력 입니다.1
2번째 정수입력 입니다.2
3번째 정수입력 입니다.3
4번째 정수입력 입니다.4
5번째 정수입력 입니다.5
Terminal will be reused by tasks, press any key to close it.
For starters this initialization of an array
int arr[5]={};
is incorrect in C. You have to write
int arr[5]={ 0 };
Secondly using the magic number 5 within the function makes the function useless in general. You need to pass to the function the size of the array.
The initial value 0
int maxnum=0,minnum=0;
of these variables makes the function even more less useful. In general the array can contain either all elements positive or all elements negative.
And you need to flush the output buffer using for example the new line character '\n' in calls of printf.
The function can be declared and defined the following way as it is shown in the demonstration program below.
#include <stdio.h>
void MaxAndMin( const int a[], size_t n, int **max, int **min )
{
*max = ( int * )a;
*min = ( int * )a;
for ( size_t i = 1; i < n; i++ )
{
if ( **max < a[i] )
{
*max = ( int *)( a + i );
}
else if ( a[i] < **min )
{
*min = ( int * )( a + i );
}
}
}
int main( void )
{
int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
int *maxPtr = NULL;
int *minPtr = NULL;
MaxAndMin( a, N, &maxPtr, &minPtr );
printf( "The maximum value is %d at position %tu\n",
*maxPtr, maxPtr - a );
printf( "The minimum value is %d at position %tu\n",
*minPtr, minPtr - a );
}
The program output is
The maximum value is 9 at position 9
The minimum value is 0 at position 0
Pay attention to that the first parameter of the function should have the qualifier const because passed arrays to the function are not changed within the function.
The main issue is that the minnum is set at zero, which would only work if array had a negative value.
Setting minimum = star[0] also would not work!!! Because in the case of str[0] having negative value, *min never gets changed.
Also, I recommend to always initialize all variables in the declaration, especially pointers (because they may theoretically cause accidental access to memory).
Full solution:
#include <stdio.h>
int MaxAndMin(int* str, int** max, int** min)
{
int i;
int maxnum = 0;
int minnum = str[0] + 1;
for(i=0; i<5; i++)
{
if(maxnum < str[i])
{
maxnum = str[i];
*max = &str[i];
}
if(minnum > str[i])
{
minnum = str[i];
*min = &str[i];
}
}
return 0;
}
int main(void)
{
int i = 0;
int len = 0;
int* maxPtr = NULL;
int* minPtr = NULL;
int arr[5]={};
for(i=0; i<5; i++)
{
printf("Enter number %d: ",i+1);
scanf("%d", &arr[i]);
}
MaxAndMin(arr, &maxPtr, &minPtr);
printf("%d",*maxPtr);
printf("%d",*minPtr);
printf("Hi");
return 0;
}
Can someone help me fixing the syntax errors in this code?
#include <stdio.h>
int result(int v, int size);
int main(void){
int arr[5], n;
for (n = -1; n < 4; n++){
arr[n] = n + 1;
printf("the product of entered values is %d", result(n, 5));
}
return 0;
}
int product(int a[]) {
int product, i;
for (i = 0; i <= sizeof(int); i++){
product *= a[i];
}
return product;
}
for (n = -1; n < 4; n++){
arr[n] = n + 1;
You start n at -1, then immediately use arr[n].
Negative indices are not allowed in C. Valid values are 0 to the size of the array-1.In otherwords, if you have an arr[5], then the valid indices are [0], [1], [2], [3], and [4].
int product(int a[]) {
int product, i;
You create a function named product and also a variable named product.
That makes it virtually impossible to refer to the proper object. Work on your name management, so that every item is unambiguous.
You are trying to call the result function, for which you have provided the forward declaration but not an actual implementation. You need to write an implementation for the result function. That is why the compiler complains about an undefined reference.
For starters the function result is declared
int result(int v, int size);
but not defined.
On the other hand, taking into account the message in this call of printf
printf("the product of entered values is %d", result(n, 5));
you mean a function that calculates a product of elements of an array like your function defined after main but that is not used
int product(int a[]) {
int product, i;
for (i = 0; i <= sizeof(int); i++){
product *= a[i];
}
return product;
}
So let's remove the declaration of the function result and declare before main a function with name product because the name result is not enough informative.
The function deals with an array. We need to pass to the function the number of elements in the array. As the array itself will not be changed within the function then it should be declared with the qualifier const
Also a product of integer numbers of the type int can be too big to be stored in an object of the type int.
So it is better to declare the return type of the function at least like long long int (or even like double or long double).
Thus the function declaration can look like
long long int product( const int a[], size_t n );
The function can be defined the following way
long long int product( const int a[], size_t n )
{
long long int result = n == 0 ? 0 : 1;
for ( size_t i = 0; i < n; i++ )
{
result *= a[i];
}
return result;
}
As for your function product then you forgot to initialize the variable product
int product, i;
The condition in the for loop
for (i = 0; i <= sizeof(int); i++){
does not make a sense because the expression sizeof( int ) does not yield the number of elements in an array.
Try to not use magic numbers like 5 in this declaration
int arr[5], n;
in your programs. Use named constants.
Indices of arrays always start from 0. So this loop
for (n = -1; n < 4; n++){
where the variable n is used as an index does not make sense.
Also this call of printf
printf("the product of entered values is %d", result(n, 5));
must be placed outside the for loop and in the the call of the function result that is used as an argument of the function printf
result(n, 5)
you even are not using the array.
Thus the program can look the following way
#include <stdio.h>
long long int product( const int a[], size_t n );
int main(void)
{
enum { N = 5 };
int a[N];
for ( size_t i = 0; i < N; i++ )
{
a[i] = i + 1;
}
printf( "The product of entered values is %lld", product( a, N ) );
return 0;
}
long long int product( const int a[], size_t n )
{
long long int result = n == 0 ? 0 : 1;
for ( size_t i = 0; i < n; i++ )
{
result *= a[i];
}
return result;
}
The program output is
The product of entered values is 120
In the book I am studying it says that if I pass a vector to a function, the name of the vector is always treated as a pointer.
In fact it's so.
But I can't understand why in the first function the const clause is allowed by the compiler, while in the second function (where I use pointers to search for the maximum value between the elements) no.
In the functions I would simply like to protect against the modification of the vector.
#include <stdio.h>
int find_largest(const int a[], int n);
int find_largest_with_pointer(const int *vettore, int n);
int main(void) {
int my_number[] = {5, 7, 90, 34, 12};
int n = sizeof(my_number) / sizeof(my_number[0]);
int *pmy_number = my_number;
printf("%d\n", find_largest(my_number, n));
printf("%d\n", find_largest(pmy_number, n));
printf("%d\n", find_largest_with_pointer(my_number, n));
printf("%d\n", find_largest_with_pointer(pmy_number, n));
return 0;
}
int find_largest(const int a[], int n) {
int i, max;
max = a[0];
for(i = 0; i < n; i++)
if(a[i] > max)
max = a[i];
return max;
}
int find_largest_with_pointer(const int *vettore, int n) {
int *i, max = *vettore;
for(i = vettore; i < vettore + n; i++)
if(*i > max)
max = *i;
return max;
}
Since vettore is a pointer to const int, you must make i have the same type.
const int *i;
int max = *vettore;
for(i = vettore; i < vettore + n; i++)
Short Version: Adding a const qualifier will address the compiler warning.
int find_largest_with_pointer(const int *vettore, int n) {
// int *i, max = *vettore;
const int *i ;
int max = *vettore;
...
}
Long Version:
In the second function, you use two variables. Expanding the code a little bit
int *i ;l
it max = a[0] ;
for (
i = vettore;
i < vettore + n;
i++
) { ... }
Note the line i = vettore, which will attempt to copy the 'const int * vettoreinto non-const 'int *i. This has the potential of allowing modification to the const vector (e.g. *i = 5), and the compiler complain:
c.c:33:11: warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
for(i = vettore; i < vettore + n; i++)
Solution is simple: add const qualifier on const int *i. See above.
#include <stdio.h>
int min(int pArray[], int nrOfArrayElements)
{
min = pArray[0];
for (int i = 1; i < nrOfArrayElements; i++)
{
if (pArray[i] < min)
{
min = pArray[i];
}
}
return min;
}
int main()
{
int x[10] = { 2,3,4,5,1,6,9,8,7,0 };
int sizeOfArray, sizeOfElement, nrOfArrayElements;
sizeOfArray = sizeOf(x);
sizeOfElement = sizeOf(x[0]);
nrOfArrayElements = sizeOfArray / sizeOfElement;
int min = min(x[10],nrOfArrayElements);
printf("smallest Array = %d", min);
return 0;
}
The following errors appear whilst trying to pass my array from main to my function min im not quite sure why pArray[0] is classified as a pointer when I am just trying to get the element on that position.
main.c:13:9: error: lvalue required as left operand of assignment
min = pArray[0];
main.c:19:8: error: lvalue required as left operand of assignment
min = pArray[i];
main.c:32:16: error: called object ‘min’ is not a function or function pointer
int min = min(x[10],nrOfArrayElements);
You have 3 problems.
You are calling function sizeOf, while the actual name is sizeof. (Note the Capitalization)
You are using an integer min and also a function min. Both identifiers cannot have the same name. I have changed the integer to min2.
In the function call to min, you are calling it with min(x[10],nrOfArrayElements). Since the first parameter is an array of int, you need to pass the base address of the array, i.e. min(x,nrOfArrayElements)
Final code is below.
int min(int pArray[], int nrOfArrayElements)
{
int min2;
min2 = pArray[0];
for (int i = 1; i < nrOfArrayElements; i++)
{
if (pArray[i] < min2)
{
min2 = pArray[i];
}
}
return min2;
}
int main()
{
int x[10] = { 2,3,4,5,1,6,9,8,7,0 };
int sizeOfArray, sizeOfElement, nrOfArrayElements;
sizeOfArray = sizeof(x);
sizeOfElement = sizeof(x[0]);
nrOfArrayElements = sizeOfArray / sizeOfElement;
int min2 = min(x,nrOfArrayElements);
printf("smallest Array = %d", min2);
return 0;
}