#include <stdio.h>
int ABC(int &n) // Error=> expected ')'
{
printf("n=");
scanf("%d",&n);
}
Help me, please! Thank you :)
Take a look to Question 4.11 of C-FAQ
Q: Does C even have ``pass by reference''?
A: Not really.
Strictly speaking, C always uses pass by value. You can simulate pass
by reference yourself, by defining functions which accept pointers and
then using the & operator when calling, and the compiler will
essentially simulate it for you when you pass an array to a function
(by passing a pointer instead, see question 6.4 et al.).
Another way of looking at it is that if an parameter has type, say,
int * then an integer is being passed by reference and a pointer to an
integer is being passed by value.
Fundamentally, C has nothing truly equivalent to formal pass by
reference or C++ reference parameters. (On the other hand,
function-like preprocessor macros can provide a form of ``pass by
name''.)
See also questions 4.8, 7.9, 12.27, and 20.1.
To simulate a pass by reference:
int ABC(int *n)
{
printf("n=");
scanf("%d", n);
printf("%d\n", *n);
return 0;
}
Call it using &:
int x;
ABC(&x);
You are not able to get the arguments as address using the ampersand(&). So you can use the
pointer to get the address of one variable.
int ABC(int *n)
{
scanf("%d",n);
}
While passing to that function, you have to pass the address of the variable.
int a;
ABC(&a);
The & is the address of operator, it can't be passed as argument to a function.
If you want to fix your code, you need to pass the argument n without &
#include <stdio.h>
int ABC(int n)
{
printf("n=");
scanf("%d",&n);
}
The same code i tried in c++ it worked just return a value and see hope this may give you an idea
int ABC(int &n)
{
printf("n=")
scanf_s("%d",&n);
return n;
}
Related
The title describes what I'm trying to do, but I'm getting the error message that I never declared base1. I actually know this, but I'm not exactly sure how to actually fix the problem.
int getBase1(void);
int setBase1(double);
int main(void){
getBase1();
setBase1(base1);
}
int getBase1(void){
printf("Please enter the length of a base: ");
return;
}
int setBase1(double base1){
scanf("%lf", &base1);
}
You must use pointer, otherwise the variable inside the method will not point to the same memory adress. Using pointer you'll be putting the value inside the memory address of the variable that you pass in the function call.
One more thing, this way you will not need return values.
Try this way:
#include <stdio.h>
void getBase1(void);
void setBase1(double *base1);
int main(void){
double base1;
getBase1();
setBase1(&base1);
printf("%lf", base1);
}
void getBase1(void){
printf("Please enter the length of a base: ");
}
void setBase1(double *base1){
scanf("%lf", base1);
}
Seems like you're quite new to C programming. Here's a thing, you simply can't use scanf to modify a value of a main function variable without using pointers. If you read about scanf, you would find out that scanf requires the memory address of a variable; that's why scanf is able to read the format string and modify your variable. So what you're trying to achieve is pretty much similar to scanf, you have to pass the address of base1; first of all declare it! Since that's what compiler is crying about. Do the following things:
Declare and pass the address of the variable you want to modify. Pass the address of base1 like this:
double base1;
getBase1();
setBase1(&base1);
In the function getBase1 you're doing a void return, but your function signature tells the compiler that you would return an int. So your functions should look like this:
void getBase1(void);
void setBase1(double *);
Since your setBase1 is receiving an address, there is no need for an ampersand(&). Simply pass the pointer value received:
void setBase1(double *pBase) { scanf("%lf", pBase); }
You have many errors in your code, first int main(), should have the return type and your function doesn't return anything either. base1 is not declared.
error: ‘base1’ undeclared (first use in this function)
setBase1(base1);
^
where is the base1 in your main function?
Its basic your passing base1 as an argument to setBase1 but base1 is not declared.
I have created an array of function pointers to swap two variables.
pointer pointing to these functions namely: swap1, swap2. swap3 and swap4.
swap2 is swaping using pointer passed as arguments.
but while declaring the function pointer, only int and int are passed as arguments. after compiling this causes many warnings.
so do we have a better way of passing the argument, where we put condition in function call itself.
code is given below.
#include <stdio.h>
int swap1(int ,int );
int swap2(int* ,int* );
int swap3(int ,int );
int swap4(int, int);
int swap1(int a,int b)
{
int temp=a;
a=b;
b=temp;
printf("swapped with 3rd variable :%d, %d\n", a,b);
}
int swap2(int *a,int *b)
{
int temp = *a;
*a = *b;
*b = temp;
printf("swapped with pointer :%d, %d\n", *a,*b);
}
int swap3(int a,int b)
{
a+=b;
b=a-b;
a-=b;
printf("swapped with 2 variable :%d, %d\n", a,b);
}
int swap4(int a,int b)
{
a=a^b;
b=a^b;
a=a^b;
printf("swapped with bitwise operation :%d, %d\n", a,b);
}
int main()
{
int ch;
int a=3;
int b=4;
printf("enter the option from 0 to 3\n");
scanf("%d",&ch);
int (*swap[4])(int, int) ={swap1,swap2,swap3,swap4};// function pointer
/*can we pass something like int(*swap[4]( condition statement for 'pointer to variable' or 'variable')*/
if (ch==1)// at '1' location, swap2 is called.
{
(*swap[ch])(&a,&b);//passing the addresses
}
else
{
(*swap[ch])(a,b);
}
return 0;
}
some warnings are as follows.
at line 36 in file '9e748221\script.c'
WARNING: found pointer to int where int is expected
at line 47 in file '9e748221\script.c'
WARNING: found pointer to int where int is expected
at line 47 in file '9e748221\script.c'
Well yes. There are a number of problems with your code, but I'll focus on the ones to which the warnings you presented pertain. You declare swap as an array of four pointers to functions that accept two int arguments and return an int:
int (*swap[4])(int, int)
Your function swap2() is not such a function, so a pointer to it is not of the correct type to be a member of the array. Your compiler might do you a better favor by rejecting the code altogether instead of merely emitting warnings.
Having entered a pointer to swap2() into the array anyway, over the compiler's warnings, how do you suppose the program could call that function correctly via the pointer? The type of the pointer requires function arguments to be ints; your compiler again performs the dubious service of accepting your code with only warnings instead of rejecting it.
Since the arguments in fact provided are the correct type, it might actually work on systems and under conditions where the representations of int and int * are compatible. That is no excuse, however, for writing such code.
Because pointers and ints are unchanged by the default argument promotions, one alternative would be to omit the prototype from your array declaration:
int (*swap[4])() = {swap1,swap2,swap3,swap4};
That says that each pointer points to a function that returns int and accepts a fixed but unspecified number of arguments of unspecified types. At the point of the call, the actual arguments will be subject to the default argument promotions, but that is not a problem in this case. This option does prevent the compiler from performing type checking on the arguments, but in fact you cannot do this correctly otherwise.
Your compiler might still warn about this, or could be induced to warn about it with the right options, but the resulting code nevertheless conforms and does the right thing, in the sense that it calls the pointed-to functions with the correct arguments.
To deal with the warnings first: You declare an array of functions which take int parameters. This means that swap2 is incompatible with the type of element for the array you put it in. This will generate a diagnostic.
Furthermore, when you call one of the functions in the array, the same array declaration tells the compiler that the parameters need to be ints not pointers to int. You get two diagnostics here, one for each parameter.
To fix the above all your functions need to have compatible prototypes with the element type of the array. Should it be int or int*? This brings us to the other problem.
C function arguments are always pass by value. This means that the argument is copied from the variable onto the stack (or into the argument register depending on the calling convention and argument count - for the rest of this post, I'll assume arguments are placed on the stack for simplicity's sake). If it's a literal, the literal value is put on the stack. If the values on the stack are changed by the callee no attempt is made by the caller, after the function returns, to put the new values back in the variables. The arguments are simply thrown away.
Therefore, in C, if you want to do the equivalent of call by reference, you need to pass pointers to the variables you use as arguments as per swap2. All your functions and the array should therefore use int*. Obviously, that makes one of swap1 and swap2 redundant.
The correct array definition is
int (*swap[4])(int*, int*) = {swap1, swap2, swap3, swap4};
and the definition of each function should be modified to take int* parameters. I'd resist the temptation to use int (*swap[4])() simply because it circumvents type safety. You could easily forget the & in front of an int argument when the called function is expecting a pointer which could be disastrous - the best case scenario when you do that is a seg fault.
The others have done great work explaining what the problems are. You should definitely read them first.
I wanted to actually show you a working solution for that sort of problem.
Consider the following (working) simple program :
// main.c
#include <stdio.h>
void swap1(int* aPtr, int* bPtr) {
printf("swap1 has been called.\n");
int tmp = *aPtr;
*aPtr = *bPtr;
*bPtr = tmp;
}
void swap2(int* aPtr, int* bPtr) {
printf("swap2 has been called.\n");
*aPtr += *bPtr;
*bPtr = *aPtr - *bPtr;
*aPtr -= *bPtr;
}
int main() {
int a = 1, b = 2;
printf("a is now %d, and b is %d\n\n", a, b);
// Declare and set the function table
void (*swapTbl[2])(int*, int*) = {&swap1, &swap2};
// Ask for a choice
int choice;
printf("Which swap algorithm to use? (specify '1' or '2')\n>>> ");
scanf("%d", &choice);
printf("\n");
// Swap a and b using the right function
swapTbl[choice - 1](&a, &b);
// Print the values of a and b
printf("a is now %d, and b is %d\n\n", a, b);
return 0;
}
First of, if we try to compile and execute it:
$ gcc main.c && ./a.out
a is now 1, and b is 2
Which swap algorithm to use? (specify '1' or '2')
>>> 2
swap2 has been called.
a is now 2, and b is 1
As myself and others mentioned in answers and in the comments, your functions should all have the same prototype. That means, they must take the same arguments and return the same type. I assumed you actually wanted to make a and b change, so I opted for int*, int* arguments. See #JeremyP 's answer for an explanation of why.
I just started learning functions and passing the parameters. so i am kind of new to this. Here, in the following programming, i am changing the values of a[] which is a formal parameter. even though, the sort function is not returning anything. how are the elements in numberArray[] are getting sorted even though the sort function just dealing with the formal parameters?
#include<stdio.h>
void sort(int[],int);
int main(void)
{
int n;
printf("enter the number of elements : ");
scanf("%d",&n);
int numberArray[n];
printf("enter %d numbers :\n",n);
for(int i=0;i<n;i++)
scanf("%d",&numberArray[i]);
sort(numberArray,n);
printf("sorted list of numbers are :\n");
for(int i=0;i<n;i++)
printf("%d\n",numberArray[i]);
return 0;
}
void sort(int a[],int n)
{
int i,j,temp;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[j];
a[j]=a[i];
a[i]=temp;
}
}
}
}
I would like to compare the above program with a simple program as follows.
#include<stdio.h>
void nothing(int);
int main(void)
{
int a;
printf("enter the value : ");
scanf("%d",&a);
nothing(a);
printf(" a = %d",a);
return 0;
}
void nothing(int b)
{
b=b+2;
}
In this program, the value of a is not changing. Why?
In C array parameters to functions are a fiction. Arrays don't get passed to functions; the parameter is treated as a pointer.
So in your example a is really an int*.
Personally, I think that function parameters declared as arrays is almost always a bad idea, since it doesn't model what is really being passed to the function. Until you understand what is really happening, it can cause confusion of the sort you ran into. It also commonly causes problems with people who try to obtain he size of the array passed to a function using the sizeof operator - that doesn't work since sizeof will return the size of a pointer type, not the actual array type.
The one situation where I think array formal arguments might make sense is with multi-dimension arrays, where the pointer arithmetic can be helpful.
Note that C99 introduced variable length arrays (VLAs) which can change much of this. VLAs are different animals, but because support for them came rather late (even after C99 was standardized, it took a while for may implementations to support them properly). This answer doesn't necessarily apply to passing VLAs as arguments to functions.
C passes by value ie
void nothing(int b) {
b=b+2;
}
is getting a copy of the integer. If you want to see the int change you need to pass it's address ie
void nothing(int *b) {
*b = *b + 2;
}
You pass the address as following
nothing(&a);
In the program you reference this function...
void sort(int a[],int n)
is taking a pointer to an array of integers as it's first argument so any change to it in the function changes the actual memory it points to
Ok so, I'm trying to write a program which numerically evaluates integrals using Simpson's 3/8 rule. I'm having issues passing the values from Integral *newintegral to the simpson() function. I'm not massively confident in my understanding of structures and pointers, and I've been reviewing the lecture notes and checking online for information all day and I still can't understand why it's not working.
At the moment when I try to build my program it comes up with a number of errors, particularly: on line 46 "expected expression before Integral" and on most of 55-63 "invalid type of argument of '->' (have 'Integral') I don't understand why the first one is occurring because all my lecturers examples of this type of thing, when passing a structure to a function just have the syntax func(Struct_define_name individual_struct_name). I thought this is what I was doing with mind (Integral being the name of the structure type and i being the specific structure) but obviously not.
I think these two problems are connected so I included all of my code for context, however the lines which actually have errors are 46 and 55-63 as mentioned above. I've probably defined the structure wrong in the first place or something though.
(Incidentally the maths in the simpson() function doesn't actually work properly now anyway, but that's not something I'm concerned about)
Also I tried looking at other similar questions but I didn't understand what the other code was doing so I couldn't extrapolate how to fix my code from that. I know this isn't very relevant to other people but I really don't understand programming well enough to try and phrase my question in a general sense...
'#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct integral {
double result, limits[2];
int degree;
double coefficients[];
} Integral;
// Prototype of function that calculates integral using Simpson's 3/8 rule
double simpson(Integral i);
// function (?) which initialises structure
Integral *newintegral() {
Integral *i = malloc(sizeof *i);
double lim1_in, lim2_in;
int degree_input, n;
printf("Please enter the degree of the polynomial.\n");
scanf("%d", °ree_input);
i->degree = degree_input;
printf("Please enter the %d coefficients of the polynomial, starting\n"
"from the highest power term in the polynomial.\n", (i->degree+1));
for (n=i->degree+1; n>0; n=n-1) {
scanf("%lg", &i->coefficients[n-1]);
}
printf("Please enter the upper limit of the integral.\n");
scanf("%lg", &lim1_in);
i->limits[0] = lim1_in;
printf("Please enter the lower limit of the integral.\n");
scanf("%lg", &lim2_in);
i->limits[1] = lim2_in;
return i;
}
int main() {
Integral *i = newintegral();
simpson(Integral i);
return 0;
}
double simpson(Integral i) {
int n;
double term1, term2, term3, term4;
for (n=(i->degree); n>0; n=n-1) {
term1=(pow(i->limits[1],n)*(i->coefficients[n]))+term1;
term2=(pow(((((2*(i->limits[1]))+(i->limits[0])))/3),n)*(i->coefficients[n]))+term2;
term3=(pow(((((2*(i->limits[0]))+(i->limits[1])))/3),n)*(i->coefficients[n]))+term3;
term4=(pow(i->limits[0],n)*(i->coefficients[n]))+term4;
}
i->result = (((i->limits[0])-(i->limits[1]))/8)*(term1+(3*term2)+(3*term3)+term4);
printf("The integral is %lg\n", i->result);
return 0;
}'
You're currently passing a pointer to a function that takes a single Integral argument.
Your prototype, double simpson(Integral i); tells the compiler "declare a function called simpson that returns a double and takes a single Integral referenced by the identifier i inside the function.
However, in main() you say:
int main() {
//declare a pointer to an Integral and assign it to the return of 'i'
Integral *i = newintegral();
//call the function simpson with i.
//However, you are redeclaring the type of the function argument, so the compiler will complain.
simpson(Integral i);
return 0;
}
Your call, simpson(Integral i); will not work because you are redeclaring the type of the function argument. The compiler will state:
:46:13: error: expected expression before ‘Integral’
What you really need is for simpson() to take a pointer to Integral as its argument. You have actually already handled this inside the function, (using i->) but your function prototype is telling the compiler that you are passing the whole struct Integral as the function argument.
Solution:
Change your function prototype as follows:
double simpson(Integral *i); // function returning double taking single pointer to an Integral named i.
...and change main() to look like the following:
int main(void) { //In C main has two valid definitions:
//int main(void), or int main(int argc, char **argv)
Integral *i = newintegral();
simpson(i);
return 0;
}
So in conclusion, your understanding of pointers is correct, but not how you pass a pointer to a function.
**Sidenote:
Remember to always build your code with all warnings enabled. The compiler will give you very useful diagnostics that will help you quickly find solutions to problems like this. For GCC, as a minimum, use gcc -Wall myprogram.c
Two obvious problems:-
Line 46 : simpson(Integral i);
...should be just simpson(i);. Putting a type there is simply an error.
And this, later:
double simpson(Integral i)
.. tells the compiler to pass in Integral object yet you use the indirection operator i.e i->limits as though you'd been passed a pointer. The easiest fix is to make the function expect a pointer, like this:
double simpson(Integral *i)
I am really at a loss about this program.I want it to return the address of an integer array of 5 elements.But it just wont' work.How to make a C function return the address of an array instead of the address of its first element(base address)?I know both are same numerically but their types are different,that's why I ask.
Also to put it precisely, how to declare the prototype of such functions?I understand how to declare the argument part of the prototype (using abstract declarators) but just don't know how to declare the return type if we are to return addresses of arrays or functions.I only know that if we place a '*' before function name in declaration that it means the function returns a pointer to the respective primary data type like int,char or float.
#include<stdio.h>
int (*)[5]fun(int (*)[5]);
int main(void)
{
int arr[5];
printf("%u",fun(&arr));
}
int (*)[5]fun(int (*arr_add)[5])
{
return arr_add;
}
HELLO!! DANIEL FISCHER Thanks for your answer.You answered it exactly and in a concise way.But I am choosing H2CO3 's answer as that brilliant Hungarian kid took the trouble to explain it to me in detail through chat.It's really hard to pick the best answer when so many bright people are answering.Thanks everyone!!
Perhaps explaining how it works is of some use.
The idea behind C's declaration syntax is that "declaration mimics use". So you want
a function
fun( )
taking a pointer to an array of five int
fun(int (*arr)[5]) // or without argument name fun(int(*)[5])
and returning a pointer
(*fun(int (*arr)[5]))
to an array of five
(*fun(int (*arr)[5]))[5]
int
int (*fun(int (*arr)[5]))[5];
Or, you can also go from the result, that should be a pointer to an array of five int,
int (*result)[5];
and substitute result with the call (result = fun(arr))
int (*fur(arr))[5];
and then add the type of the argument/replace the argument with its type:
int (*fun(int(*)[5]))[5];
Here you are:
int (*fun(int (*arr)[5]))[5]
{
return arr;
}
If you want to return the address of the first element (as opposed to the address of the array itself), that's a different type:
int *fun(int (*arr)[5])
{
return &(*arr)[0];
}
This is wrong:
printf("%u",fun(&arr));
It should really be:
printf("%p", (void*)fun(&arr));
As for the address of the array, it is going to be the same as the address of its first element.
Now, the declaration and definition should really look like:
int (*fun(int(*)[5]))[5];
Fixed code:
#include<stdio.h>
int (*fun(int (*)[5]))[5];
int main(void)
{
int arr[5];
printf("%p\n", (void*)fun(&arr));
}
int (*fun(int (*arr_add)[5]))[5]
{
return arr_add;
}
ideone