Error in C program in Dynamic memory allocation - c

I am using gcc compiler in ubuntu18.10 os. And I don't know why this program is giving Error and Can't even understand the error. The Program is as follows and I presented ERRORS also.
#include<stdio.h>
#include<stdlib.h>
float Average(int*, int);
int main()
{
int *arr;
int n;
scanf("%d",&n);
float sum;
arr = (int *)malloc(n * sizeof(int));
for(int i=0;i<n;i++)
scanf("%d",&arr[i]);
sum = Average(int *arr, int n);
printf("%f\n",sum);
return 0;
}
float Average(int *arr, int size)
{
int sum;
int n = size;
printf("arr: %p\n",&arr);
printf("size: %p\n",&size);
printf("sum: %p\n",&sum);
for(int i=0;i<n;i++)
{
sum += arr[i];
}
return (sum * 1.0f) / size;
}
Errors are:
Test.c: In function ‘main’:
Test.c:16:16: error: expected expression before ‘int’
sum = Average(int *arr, int n);
^~~
Test.c:16:8: error: too few arguments to function ‘Average’
sum = Average(int *arr, int n);
^~~~~~~
Test.c:4:7: note: declared here
float Average(int*, int);
^~~~~~~
Please Help me to find out why and any reference materials to understand the concept clearly.
Thank you

sum = Average(int *arr, int n);
Type specifiers are something you give in the declaration and definition of the function, not in calls to it. You want:
sum = Average(arr, n);
Some other things you may want to check.
First, the int sum; in Average() does not initialise the value to zero, it sets it to some arbitrary value. That's not going to end well when you just add the integers to it. It should instead be:
int sum = 0;
Second, unless you're using massive arrays of floating point numbers, it's almost always better to use double for its greater range and precision.
Taking those into account, I probably would have written the function:
double Average(int *arr, int size) {
double sum = 0;
for (int i = 0; i < size; ++i)
sum += arr[i];
return sum / size;
}

When you call a function you don't specify the types of the arguments. That's a syntax error. If you look at where you call printf, you'll see that you don't specify the parameter types there. The same goes for your own functions.
So change this:
sum = Average(int *arr, int n);
To this:
sum = Average(arr, n);

Related

C error : expected expression before int (when I call the function I get error that an expression is missing)

I am getting errors that some expression is missing
#include <stdio.h>
void pairmul(int* p,int n,int sum){
int arr[n];
int q;
for(int i =0; i<=n-1; i++){
arr[i] = *(p+i);
}
for(int j = 0;j<=n-1;j++){
for(int k=j+1;k<=n-1;k++){
int temp;
if(arr[j]>arr[k]){
temp = arr[k];
arr[k] = arr[j];
arr[j] = temp;
}
}
}
if(arr[0]+ arr[1]<sum){
q = arr[0]*arr[1];
printf("%d",q);
}
else if(n<2){
printf("-1");
}
else{
printf("0");
}
return 0;
}
int main(){
int sum,n;
int array[n];
printf("Sum and Size of array");
scanf("%d %d \n",&sum,&n);
for(int i =0; i<=n-1; i++){
scanf("%d",&array[i]);
}
pairmul(&array[0], int n,int sum);
return 0;
}
pairmul(&array[0], int n,int sum);
I have error with this expression that there are very few arguments and
2nd is that there is some expression before 'int'
Could you recall the syntax of a function?
func(var1, var2, var3);
Right? But in your code pairmul(&array[0], int n,int sum);, you use this syntax:
func(var1, datatype var2, datatype var3);
That makes no sense. Change
pairmul(&array[0], int n,int sum);
into
pairmul(&array[0], n,sum);
And your code will work properly.
I think that the reason you are confused is because may have been confused by a function like macro. Eg.
#define MAKE_SQUARE_AND_STORE(datatype, var, num) datatype var = num * num
int main() {
MAKE_SQUARE_AND_STORE(int, square, 3);
printf("%d\n", square);
}
This works because macros replace text, so this code is actually converted to:
int main() {
int square = 3 * 3;
printf("%d\n", square);
}
And this code is fed into the actual compiler. Function like macros are a way different thing.
This is an even crazier macro:
#define DECLARE_SQUARE(dec, num) dec = num * num
And in this case, your weird syntax works.
DECLARE_SQUARE(int sqr, 3);
/*Preprocesses into:
int sqr = 3 * 3; */
Don't be confused my macros, macros have weird syntax because they are fed into a preprocessor first not directly to the actual true compiler. Macros can have any syntax. Proper C functions have a definite syntax. Use the definite syntax, don't forget it.

why am i getting segmentation fault when i run this code?

#include <stdio.h>
void avg_sum(double a[], int n, double *avg, double *sum)
{
int i;
sum = 0;
printf("%f", *sum);
for(i=0; i<n; i++)
*sum += a[i];
*avg = *sum/n;
}
int main()
{
double arr[2] = {0.0,1.0};
double *sum;
double *avg;
int n = 2;
avg_sum(arr, n, avg, sum);
printf("...Done...\n");
return 0;
}
Tried using both GCC(https://www.tutorialspoint.com/compile_c_online.php) and clang(from repl.it) online compilers
double *sum;
This creates a pointer to a double but it has an arbitrary value and therefore points at no dedicated memory.
In addition, in the called function, you set the sum pointer to zero (the null pointer) then try to use that pointer to dereference memory - that's a big non-no.
I'd also be wary of for(i=0; i<n-2; i++) for summing the values in the array. It's not going to include the final two which, since n is two, means it won't accumulate any of them.
The correct way to do this would be with:
void avg_sum(double a[], int n, double *avg, double *sum) {
int i;
*sum = 0; // set content, not pointer.
for(i=0; i<n; i++) // do all elements.
*sum += *(a+i);
*avg = *sum/n;
}
int main(void) {
double arr[2] = {0.0,1.0};
double sum; // ensure actual storage
double avg; // and here
int n = 2;
avg_sum(arr, n, &avg, &sum); // then pass pointers to actual storage
printf("Sum=%f, Avg=%f\n", sum, avg);
return 0;
}
This gives you, as expected:
Sum=1.000000, Avg=0.500000
Easy. In line 6 you assign 0 to sum but sum is not the actual sum but a pointer to it. When you try to print it you access invalid memory.
Edit:
BTW if you try compling with -fanalyzer you will get a warning and an explanation.
https://godbolt.org/z/W6ehh8

How to fill an array, that is defined in a function as parameter, through user input via main function?

I created a program to calculate the sum of 4 array elements. Is it possible to prompt the user to fill array elements manually during program execution and then show the sum? I can do this while not using the function, but I get stuck when I use functions. Is it still possible to do so?
If I insert a for loop inside the main function, just after variable initialization,
int data[];
int total;
int size = sizeof(data) / sizeof(data[0]);
printf("Enter array elements: ");
for(int i=0; i<size; i++) {
scanf("%d", &data[i]);
}
the compiler complains:
error: definition of the variable with array type needs an explicit size or an initializer
int data[];
^
1 error generated.
My program looks like this:
#include <stdio.h>
int sum(int data[], int size)
{
int sum = 0;
int i;
for (i = 0; i < size; i++)
sum += data[i];
return sum;
}
int main()
{
int data[] = { 1, 2, 3, 4 }; // I want user input here
int total;
int size = sizeof(data) / sizeof(data[0]);
total = sum(data, size);
printf("Sum is: %d\n", total);
return 0;
}
error: definition of the variable with array type needs an explicit
size or an initializer
int data[];
Compiler is clear, you can't do this:
int data[];
Need something like:
int data[SIZE];

warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘int (*)(int *, int *, int)’

So I'm new to SO and my question was not well recived...so I edited it to be more informative.
I'm trying to write a program that calls two functions in the main program. This is what I have so far:
#include <stdio.h>
#define N 10
int inner_product(int a[], int b[], int n);
int inner_product_reverse(int a[], int b[], int n);
int main(void) {
int a[N], b[N], i;
printf("Enter the first array of size 10: ");
for (i = 0; i < N; i++)
scanf("%d", &a[i]);
printf("Enter the second array of size 10: ");
for (i = 0; i < N; i++)
scanf("%d", &b[i]);
printf("Inner product is: %d\n", inner_product);
printf("Inner product reverse is: %d\n", inner_product_reverse);
return 0;
}
int inner_product(int a[], int b[], int n) {
int sum = 0, i;
for (i = 0; i < N; i++)
sum += (a[i] * b[i]);
return sum;
}
int inner_product_reverse(int a[], int b[], int n) {
int sum = 0, i;
for (i = 0; i < N; i++)
sum += (a[i] * b[(N-1)-i]);
return sum;
But I get the error in the title. I know that it's an issue of the difference in number of arguments called but I'm not sure how to write it in a way that will take into account all of the arguments of the functions.
Would I have to move the for loop that computes the inner product into the main somehow? Thanks.
Problem is in calling printf function as the warning already said.
printf("Inner product is: %d\n", inner_product);
printf("Inner product reverse is: %d\n", inner_product_reverse);
inner_product and inner_product_reverse are functions which return int and accepts 3 parameters: int (*)(int *, int *, int).
Now to get int result, call these 2 functions. What you did is that you passed pointer (location) of them to printf function and this is wrong.
You should rewrite your code to something similar to:
// Parameters are added and function will be called
printf("Inner product is: %d\n", inner_product(a, b, i));
printf("Inner product reverse is: %d\n", inner_product_reverse(a, b, i));

Sum of array in C

I'm working on a small program for school and can't get my array of doubles to sum properly. The specific error I'm getting is
warning C4244: 'return': conversion from 'double' to 'int', possible loss of data
on the line where sum is returned. And the sum displayed is gibberish.
The code is intended to:
fill an array of doubles with user input,
print the doubles on the screen in a column,
add up all the doubles in the array, and
print the sum onto the screen.
Code
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#define MAX_SIZE 15
void FillArray(double a[], int *i);
void PrintArray(double a[], int i);
SumArray(double a[], int *i);
int main()
{
double input[15];
int input_size;
double sum;
FillArray(input, &input_size);
PrintArray(input, input_size);
sum = SumArray(input, &input_size);
printf("The sum is %f\n", sum);
return 0;
}
void FillArray(double a[], int *i)
{
int k;
printf("Filling an array of doubles\n");
printf("How many doubles do you want to enter (<15)\n");
scanf(" %d", i);
for (k = 0; k <*i; k++)
{
printf("Enter double:\n");
scanf("%lf", &a[k]);
}
}
void PrintArray(double a[], int i)
{
int k;
printf("Printing an array of integers:\n");
for (k = 0; k<i; k++)
{
printf("%f\n", a[k]);
}
printf("\n");
}
SumArray(double a[], int *i)
{
int k;
double sum = 0;
for (k = 0; k<*i; k++);
{
sum +=a[k];
}
return (sum) ;
}
You need to specify double SumArray(...) instead of merely SumArray(...) where you declare and define the function. If you do not specify a return type, int is assumed. Specifically:
void FillArray(double a[], int *i);
void PrintArray(double a[], int i);
double SumArray(double a[], int *i);
/*^^^^^^-- add return type*/
int main()
and
double SumArray(double a[], const int numElements)
/*^^^^^^- same deal*/ /* also ^^^^^ ^^^^^^^^^^^ */
{
int k;
double sum = 0.0; /* Edit 3: 0.0 rather than 0 for clarity */
for (k = 0; k < numElements; ++k) /* no ; here! --- Edit 3: ++k for speed and good practice */
{ /* ^^^^^^^^^^^ */
sum +=a[k];
}
return (sum) ;
}
Edit Also, you can use const int numElements instead of int *i in SumArray. You don't need to modify the value inside SumArray, so you don't need the * and you can specify const. And it's a good practice to give your variables descriptive names, e.g., numElements instead of i. That will help you understand your own code when you have to maintain it later! (Ask me how I know. ;) )
To use this, you also need to change the call in main to remove the &:
sum = SumArray(input, input_size);
/* ^ no & here */
Edit 2 As #BLUEPIXY pointed out, the trailing ; on the for loop was misplaced. As a result, the {} block ran once, after the loop had completed. That would be a significant cause of the "gibberish" you saw: the effect was to set k=numElements and then set sum=a[numElements], which was a non-existent element. So the sum was being set to whatever random memory contents happened to be after a.

Resources