I am trying to a simple addition function that will take a number x from an array an and add a variable i to it, which is the iteration variable inside the for loop. Instead of adding each variable individually and producing the output of :
3, 2, 7
it produces values of
3, 5, 13.
#include <stdio.h>
int add(int x[], int y);
int main(void) {
int i;
int a[3] = {3, 1, 5};
for(i=0; i<3; i++)
{
printf("%d \t", i);
printf("%d, %d, equals %d \n", a[i], i, add(a[i], i));
}
return 0;
}
int add(int x[], int y){
return x+y;
}
Try
int add(int x, int y){
return x+y;
}
In your function definition,
int add(int x[], int y){
int x[] expects an array to be passed as the argument. By calling that with
add(a[i], i)
you're making multiple mistakes, like
passing an int value where int * is expected, so a wrong and implicit conversion from int to int * is talking place.
Inside add(), x is of type int *. So, by saying return x+y;, you're essentially again (wrongly) converting a pointer to int type.
Here, it seems, you need only one int variable. not an array. Change it (both declaration and definition) to
int add(int x, int y){
Suggestion: Turn up the compiler warnings and pay heed to them. For example, with the -Wall option enabled, you would have received a warning saying
warning: passing argument 1 of ‘add’ makes pointer from integer without a cast
printf("%d, %d, equals %d \n", a[i], i, add(a[i], i));
^
and
expected int * but argument is of type int
int add(int x[], int y);
and,
warning: return makes integer from pointer without a cast
return x+y;
^
You are using array as an argument. Please try below code:
#include <stdio.h>
int add(int x, int y);
int main(void) {
int i;
int a[3] = {3, 1, 5};
for(i=0; i<3; i++)
{
printf("%d \t", i);
printf("%d, %d, equals %d \n", a[i], i, add(a[i], i));
}
return 0;
}
int add(int x, int y){
return x+y;
}
Related
Only Value of 1st row of matrix is passing through Add().I am getting erroneous results.for Eg : matrix 1 has elements 1,2,3,4 .However when i print these values in add() ,I am getting 1,2,0,0.
#include <stdio.h>
int main()
{
int arr[100][100], arr1[100][100];
int m, n, x, y, z;
printf("\n Enter order of matrix");
scanf("%d %d ", &m, &n);
//ENTRY OF MATRIX
printf("\n Enter Values of Matrix 1");
for (x = 0; x < m; x++)
{
for (y = 0; y < n; y++)
scanf("%d ", &arr[x][y]);
}
printf("\n Enter Value of Matrix two ");
for (x = 0; x < m; x++)
{
for (y = 0; y < n; y++)
scanf("%d ", &arr1[x][y]);
}
add(m, n, arr, arr1);
return 0;
}
void add(int m, int n, int a[m][n], int b[m][n])
{
int x, y;
for (x = 0; x < m; x++)
{
for (y = 0; y < n; y++)
printf("%d ", a[x][y]);
printf("\n");
}
}
In C, functions must be declared before use and the type of the arguments must match between declaration and call.
In OP's code, a couple of 2D array declared as
int arr[100][100];
are passed to a function defined after main() as
void add(int m, int n, a[m][n], b[m][n]) { /* ... */ }
Generating two issues:
add() is used in main(), but it's not declared before, it's defined only after.
arr and arr1 are 2D arrays of 100 x 100 ints, but function add() as written, accepts two Variable Length Arrays of size m x n.
OP have two ways to fix, either they change the interface of the function and declare it before main(), like this:
void add(int m, int n, a[][100], b[][100]); // and define after main
Or change the declarations of arr and arr1:
// includes...
void add(int m, int n, a[m][n], b[m][n]);
int main(void)
{
int m, n;
// ...
// read n and m before using them to declare the two VLA
int arr[m][n], arr1[m][n];
// ...
add(m, n, arr, arr1);
// ...
}
void add(int m, int n, a[m][n], b[m][n])
{
// ...
}
First of all, please fix your indentation, it makes your code really hard to read.
This error is because you can't use a function that has not been declared.
To fix that, either add a prototype after your includes :
void add(int m,int n,int a[m][n],int b[m][n]);
Or try to put your whole function before your main.
I have fixed some problem in your code.I have added declaration before main().
void add(int m,int n,int a[m][n],int b[m][n]);
Also, I have removed the whitespace into scanf function.
int main()
{
int arr[100][100],arr1[100][100];
int m,n,x,y,z;
printf("\n Enter order of matrix");
scanf("%d %d",&m,&n);
//ENTRY OF MATRIX
printf("\n Enter Values of Matrix 1");
for(x=0;x<m;x++)
{
for(y=0;y<n;y++)
scanf("%d",&arr[x][y]);
}
printf("\n Enter Value of Matrix two ");
for(x=0;x<m;x++)
{
for(y=0;y<n;y++)
scanf("%d",&arr1[x][y]);
}
add(m,n,arr,arr1);
return 0;
}
void add(int m,int n,int a[m][n],int b[m][n])
{
// Your operation
}
I wrote the same code in PHP, the value of 5 got incremented, but
why doesn't the value get incremented in C?
int foo(int x){
x++;
}
int main( ){
int y = 5;
foo(y);
printf("value of y = %d\n", y);
}
In C passing arguments is done by value rather than by reference. That is, the number that the function is working with is unique to the one passed to and has its own space in memory. To get around this do
int foo(int* x){
(*x)++;
}
int main( ){
int y = 5;
foo(&y);
printf("value of y = %d\n", y);
}
You should pass the parameter by reference to function foo.
int foo(int *x){
(*x)++;
}
int main( ){
int y = 5;
foo(&y);
printf("value of y = %d\n", y);
}
Because x, y are local variables to their functions. The scope of the variable lies within the block of the function. So you can't change the value of those variables from outside the block.
Solution:
Either you declare those variables as global variables
int y;
int foo(){
y++;
}
int main( ){
y = 5;
foo();
printf("value of y = %d\n", y);
}
Or using reference you can do that
int foo(int *x){
(*x)++;
}
int main( ){
int y = 5;
foo(&y);
printf("value of y = %d\n", y);
}
Might be in PHP it is directly pass-by-reference. But C has different function calls.
If you want to increment the value in the function and it should reflect in the main function. There are two possible ways :
1.
int foo(int x)
{
return ++x; //returning the incremented value
}
2.
void foo(int *x)
{
++(*x);//this function is pass-by-reference.
}
Please let me know if there are any issue.
What you could also be doing if you want to avoid using pointers is as below
int addone(int n);
int main(void) {
int n=0;
printf("Before: %d\n", n);
n=addone(n);//assign the returned value from function to the variable 'n'
printf("After: %d\n", n);
return 0;
}
int addone(int n) {
n++;
return n;
}
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.
What my program does is it finds 2 numbers of an array that are closest to the average, one is bigger, one is smaller. It works fine, however I need to change for example **array+a to *array[a].
However, when I load the program, it crashes after I input the numbers. If I try to print *array[0], *array[1], etc. it works fine. When I try to print or just do something with *array[a], *array[b], it crashes. Thank you for your help.
#include <stdio.h>
#include <stdlib.h>
int input (int *t, int *array[]);
void calculation (int *array[], int *t, int *x, int *y);
void output (int *x, int *y);
int main()
{
int *array, t, x, y;
input (&t, &array);
calculation (&array, &t, &x, &y);
output (&x, &y);
return 0;
}
int input (int *t, int *array[])
{ int n, *ptr;
printf ("How big is the array?");
scanf ("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
int k;
printf ("Enter the numbers:");
for (k=0; k<n; k++)
{ scanf ("%d", ptr + k);
}
*t=n;
*array=ptr;
return 0;
}
void calculation (int *array[], int *t, int *x, int *y)
{ float sum=0, avg;
int min, max;
int more, less;
int a, b, c;
for (a=0; a<(*t); a++)
{sum=sum+ **array + a;
}
avg=sum/(*t);
min= *array[0];
max= *array[0];
for (b=0; b<(*t); b++)
{ if (max < (**array + b)) max=(**array + b);
if (min > (**array + b)) min=(**array + b);
}
more=max;
less=min;
for (c=0; c<(*t); c++)
{ if (((**array + c) < avg) && ((**array + c) > less)) less=(**array + c);
if (((**array + c) > avg) && ((**array + c) < more)) more=(**array + c);
}
*x=less;
*y=more;
}
void output (int *x, int *y)
{ printf("Number that is less than the average:%d\n", *x);
printf("Number that is more than the average:%d\n", *y);
}
It would be better to rethink your function prototypes a bit. It makes sense to pass a pointer to array to the input() function since you are allocating memory for it, and you want to be able to access it when you return. But you don't need to pass in the pointer to int t; instead, just return the value of n, and assign it to t in main.
There is no reason to pass a pointer to array to the function calculation(), since you are not changing the array allocation. You can also pass in the value of t from main(), since you only use this value in calculation(), but do not change it.
Similarly, the output() function only needs copies of x and y, since it does not change them.
The rule of thumb here is that you pass a pointer to a value into a function when you want to modify the value inside the function and have access to the modified value in the calling function. But you can also return a value instead of using a pointer to it.
These changes do not alter the functionality of your code, but they substantially improve its readability. You even get a sense of what is being modified in each function just by looking at the function prototypes. Well, the changes do alter the functionality in that your original **array + a was incorrect, and needed to be either *(*array + a) or (*array)[a]. But sorting that problem out should help you to appreciate the virtue of the simpler function prototypes. Here is the modified code:
#include <stdio.h>
#include <stdlib.h>
int input(int *array[]);
void calculation(int array[], int t, int *x, int *y);
void output(int x, int y);
int main(void)
{
int *array, t, x, y;
t = input(&array);
calculation(array, t, &x, &y);
output(x, y);
return 0;
}
int input(int *array[])
{ int n, *ptr;
printf("How big is the array?");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
int k;
printf("Enter the numbers:");
for (k=0; k<n; k++)
{ scanf("%d", ptr + k);
}
*array=ptr;
return n;
}
void calculation(int array[], int t, int *x, int *y)
{ float sum=0, avg;
int min, max;
int more, less;
int a, b, c;
for (a=0; a<t; a++)
{sum=sum+ array[a];
}
avg=sum/t;
min= array[0];
max= array[0];
for (b=0; b<t; b++)
{ if (max < array[b]) max=array[b];
if (min > array[b]) min=array[b];
}
more=max;
less=min;
for (c=0; c<t; c++)
{ if ((array[c] < avg) && (array[c] > less)) less=array[c];
if ((array[c] > avg) && (array[c] < more)) more=array[c];
}
*x=less;
*y=more;
}
void output(int x, int y)
{ printf("Number that is less than the average:%d\n", x);
printf("Number that is more than the average:%d\n", y);
}
Just like BLUEPIXY and Some programmer dude said, it's supposed to be (*array)[a]
I have a funtion_ptr function pointer which point to add_int function.
case 1: when lay a statement function_ptr = &add_int outside main function
--> compiler error: error C2373: 'function_ptr' : redefinition; different type modifiers (this is in )
#include <stdio.h>
int add_int(int n, int m){
return n + m;
}
int(*function_ptr)(int, int);
function_ptr = &add_int; // it's here
void main(){
int sum = (* function_ptr)(2, 3);
printf("sum = %d", sum);
_getch();
}
case 2: function_ptr = &add_int; in main function --> it is true
#include <stdio.h>
int add_int(int n, int m){
return n + m;
}
int(*function_ptr)(int, int);
void main(){
function_ptr = &add_int; // it's now here
int sum = (* function_ptr)(2, 3);
printf("sum = %d", sum);
_getch();
}
Could anyone explain for me different between the two case.
Thanks!
function_ptr = &add_int; is an assignment statement. Statements are allowed inside functions, but outside functions only declarations are allowed. Since assignment is not a declaration, the compiler issues an error.
If you want to assign the pointer as part of its declaration/definition, you could combine the declaration and the assignment, like this:
#include <stdio.h>
int add_int(int n, int m){
return n + m;
}
int(*function_ptr)(int, int) = &add_int;
int main(){
int sum = (* function_ptr)(2, 3);
printf("sum = %d", sum);
return 0;
}
Demo.
You don't need the & in the assignment statement, the function's name (add_int) IS its address... and the assignment statement should be within the bounds of a function.
Here's an example that works:
#include <stdio.h>
int add_int(int n, int m);
int(*function_ptr)(int, int);
void main(){
function_ptr = add_int;
int sum = (* function_ptr)(2, 3);
printf("sum = %d", sum);
getc(stdin);
}
int add_int(int n, int m){
return n + m;
}