error on Visual c++ - c++

void input(int B[XAM][XAM])
{ int i,j,a;
for (i=0;i<3;i++) {
for (j=0; j<3; j++) {
scanf("%d",&B[i][j]);
}
}
for (i=0;i<3;i++) {
for (j=0; j<3; j++) {
printf("%d ",B[i][j]);
}
printf("\n");
}
}
void main()
{
#define XAM 3
int pilih,A[10],B[3][3],i,j;
input(&B[XAM][XAM]);
for (i=0;i<3;i++) {
for (j=0; j<3; j++) {
printf("%d ",B[i][j]);
}
printf("\n");
}
getch();
}
why when i try to run the program, I already used "Pass by reference", but still when I call the output from void main, the output didn't the same as my input from the procedure,
but if I call the output from the procedure, there is no problem
can someone help me why pass the reference didn't work?
thanks

you are passing the address (&) of [3][3] element of B using:
&B[3][3]
Just write
input(B);
Note that passing by reference is not done when you are calling funtcion, but when you are defining, so:
int foo(Foo& f);
passes f as reference when using it simply like foo(f);
But
int foo(Foo f);
in case where Foo is not a pointer (your B is a pointer) would end in compilation error, when trying foo(&f).
Also it would be good if you used XAM constant in B definition
B[3][3] -> B[XAM][XAM]
And turn on warnings in your compilator!

You want to pass the array by reference.
Whether or not a function parameter is passed by reference or by value is decided at the function's signature. You have to change the parameter type such that it's a reference to an array. That's done by adding the ampersand & to the parameter name.
For arrays, parentheses need to be added which needs getting used to:
void input(int (&B)[XAM][XAM]) {
// ...
}
When calling that function, simply pass B without mentioning the dimensions or using the & operator (that does something different when used at values!). That means, calling the function is written as if the argument was passed by value (no syntactical difference there), but of course it is passed by reference since the function's signature says so.
input(B);
Indeed, passing arrays by reference is the only way to pass an array as an array. Otherwise (if your parameter looks like int B[XAM][XAM]), only a pointer to the first element is actually passed, and it isn't treated as an array within the function. You can easily check how it is treated in the function body by using the sizeof operator.
Related question: Passing an array by reference

Related

New operator outside main function - C++

Why this code is working:
//Things
int **A;
main(){
//things
A = new int*[n];
for (int i = 0; i < n; i++) {
A[i] = new int[m];
}
// things
}
And this code isn't working:
//Things
int **A;
void functionOutsideMain(int **A,int n, int m){
A = new int*[n];
for (int i = 0; i < n; i++) {
A[i] = new int[m];
}
}
main(){
//Things
functionOutsideMain(A,n,m);
//Things
}
When I use new operator outside main function in a separate function it won't work.
But if I use new operator inside main funcion it works.
Can you explain me why this is happening?
or
If I'm doing something wrong.
In the first example, A is just a global variable, which main() uses directly.
In the second example, functionOutsideMain() has its own A parameter which it uses, whereas main() still uses the global A variable instead.
functionOutsideMain() takes its A parameter by value. When main() passes in the global A variable to functionOutsideMain(), a copy of that A is made, and so any value that functionOutsideMain() assigns to its A parameter will not be applied to the global A variable, which is why main() does not see the change.
To do what you are attempting, you need to have functionOutsideMain() take its A parameter by reference instead:
void functionOutsideMain(int** &A, int n, int m)
Now, any value functionOutsideMain() assigns to its A parameter will be assigned to the global A variable, and thus will be seen by main().
Hey I didn't get what you meant by not working, but the possible solutions to the problems could be
No need to pass A again to functionOutsideMain since A is already global
When you pass A to functionOutsideMain, the actual parameter A becomes the formal parameter A, and now here's the problem, in C there is only pass by value(unlike pass by reference in C++). So when you pass A to the function, a new pointer gets created in the function and when you allocate a chunk of memory to it, the new pointer points to that memory and not the old pointer that you are using in main function.
One possible solution for this would be
void function_outside_main(int ***A, int n, int m) {
int **Aptr = (*A);
// And then use Aptr to allocate memory as you did
}
Else don't pass A as function parameter since it's a global variable

Copy member value on stack or access it with pointer?

So I got a structure, that holds an integer. I usually create that structure on the heap. If I now pass a pointer to such a structure into a function and use the integer member, would it be faster if I at first copied the members value on the stack and use that local variable in the function, or should I access the member through the pointer? What is potentially faster? Obviously I dont want to modify the member value. Code example:
Sample structure:
struct sample_s
{
int sample_member;
}
Way 1:
void sample_func(struct sample_s *sample_instance)
{
for(int i = 0; i < 1000; i++)
{
printf("%d", sample_instance->sample_member);
}
}
Way 2:
void sample_func_two(struct sample_s *sample_instance)
{
int a = sample_instance->sample_member;
for(int i = 0; i < 1000; i++)
{
printf("%d", a);
}
}
In your specific case, sample_func_two is potentially faster. This is because you're calling an external function, printf:
printf("%d", sample_instance->sample_member);
The compiler probably doesn't know that this call won't modify *sample_instance1, so it will reload sample_member from memory each time through the loop.
Now as for whether that makes an actual difference in the running time of your program, you'll have to benchmark it yourself.
1 The compiler doesn't know because it can't see the code of printf (it's in a library somewhere) and printf is not declared pure. In fact, printf can't be declared pure because depending on the format string it may write through its arguments (with %n).

Working of function pointers [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
In this Program, I am unable to understand the declaration of the "sum" function.
Please explain what is happening while calling the sum function and while declaring the function.
#include<iostream.h>
#include <conio.h>
int sum(int(*)(int),int);
int square(int);
int cube(int);
void main()
{
clrscr();
cout<<sum(square,4)<<endl;
cout<<sum(cube,4)<<endl;
getch();
}
int sum(int(*ptr)(int k),int n)
{
int s=0;
for(int i=1;i<=n;i++)
{
s+=(*ptr)(i);
}
return s;
}
int square(int k)
{
int sq;
sq=k*k;
return k*k;
}
int cube(int k)
{
return k*k*k;
}
The parameter is a function pointer - you should read here for an introduction, and heres a relevant SO post.
The idea is that you can pass around a function as a value - so you can make other general functions that you can give a specific function to in order to change the effect. An example would be map from functional programming.
Specifically in your case, the sum function takes this function pointer in order to sum a function of the values in the list given to it, rather than just the values themselves. This is demonstrated by passing it eg. a pointer to the square function, which will make it sum squares of the values given to sum.
This is the reason why some people does not like pointers in C and C++. See my explanation below in your program:-
#include<iostream.h>
# include <conio.h>
void main()
{
clrscr();
int sum(int(*)(int),int);// Here first parameter in `sum` is a pointer to a function which return type is int. `int(*)(int)` here int(*) is function pointer and (int) is its parameter type.
int square(int);
int cube(int);
cout<<sum(square,4)<<endl;// Now you are passing address of function `square` as first parameter and its parameter 4, like square(4)
cout<<sum(cube,4)<<endl; // Here you are passing address of function `cube` as parameter and 4 as parameter to cube function
getch();
}
int sum(int(*ptr)(int k),int n)
{
int s=0;
for(int i=1;i<=n;i++)
{
s+=(*ptr)(i); //This `ptr` is nothing but the address of function passed to sum
//hence it execute like below
//When you are calling function `sum` with function pointer `square` as first parameter
//it execute like `s = s + square(i);`
//Now at the second call to `sum` it execute like `s = s + cube(i);`
}
return s;
}
// The method sum
// First argument: a pointer to a function which accepts one integer
// as argument and returns an integer
// Second argument: an integer
int sum(int(*)(int),int);
That is why when you call sum in this line:
cout<<sum(square,4)<<endl;
You pass square as the first argument and since square is like this:
int square(int k)
{
}
it satisfies the call because it is a function which accepts one integer as argument and returns int.
Then inside the sum method, it calls the function which you passed in as the first argument like this (please read my comments inline for clarity):
int sum(int(*ptr)(int k),int n)
{
int s=0;
for(int i=1;i<=n;i++)
{
// Calls the function pointer (square in this case) and sends i to
// it as argument. It then takes the return value and adds it to s.
s+=(*ptr)(i);
}
return s;
}
Here are the different parts:
Here is another example to help you:
// fcnPtr is a pointer to a function that takes no arguments and returns an integer
int (*fcnPtr)();

C++ function input argument by reference vs by pointer

I am new to C++ and have done only MATLAB earlier.
My Q is about the input argument of the following functions, which call variables by value,reference and pointer.
void SwapbyValue (int a, int b){
// Usual swapping code
}
void SwapbyRef (int &a, int &b){
// Usual swapping code
}
void SwapbyPoint(int *a,int *b){
//Usual swapping code
}
Since my Q isn't about how the above functions work but rather about how I call them, I've left out the code. So, I understand we call the above functions by typing SwapbyRef (i1,i2),SwapbyRef (i1,i2) and SwapbyPoint(&i1,&i2) when i1 and 12 are int.
That confuses me the life out of me. Okay, I get that the first function takes in values and makes sense. But in the second one, calling by just i1 and i2 doesn't make sense as when the function is defined, we set its input as &a and not just a but it still runs. Again in the third, we set the input argument as a pointer i.e. *a but we're passing an address &a (like 0x7956a69314d8) when we call it.
Why does it run when we pass the wrong kind of input to the function?
For example,a Matlab analogy,it looks like passing a char to a int function. Help!
int &a is a reference to an int, meaning, it will accept all int variables that already exist. What you cannot do is for example SwapbyRef(4, 5) using SwapbyRef (int &a, int &b), because 4 and 5 are temporary ints that do not exist somewhere in memory as variables.
Btw, you should probably just look up what a reference in c++ is. That would help you most, I think.

Returning function parameter, possible, bad style?

So I just had a thought, is it possible to return a parameter sent when a function is called. And if it is, is this considered fine or is it bad style?
Example:
int main()
{
...
int value = 1;
value = Foo(value);
...
}
int Foo(int i)
{
i = i * 2;
return (i);
}
As the parameter is being passed in and returned by value, this is fine - there is an implicit copy occurring when you call the function and when it returns.
For example
int value=1,other=0;
other=Foo(value);
other is now 2, value will still be 1
If you were passing in a reference or pointer then you would potentially run risks.
e.g. if the signature of Foo was
int Foo( int &i )
Then after the code chunk I used above, both other and value would be 2
There's no problem with "returning a parameter" in your example. You are not really "returning a parameter" at all. You are simply using the parameter in the argument expression of return. It is the result of that expression (the value of i) that gets returned, not the parameter itself.
One can argue that the "undesirable" property of your code sample is the fact that you are modifying the parameter inside the function, i.e. you are using the parameter as an ordinary local variable. There's nothing formally wrong with it, but sometimes people prefer to preserve the original parameter values throughout the function body. I.e. from that point of view your function would look better as
int Foo(int i)
{
return i * 2;
}
or as
int Foo(int i)
{
int i2 = i * 2;
return i2;
}
but, again, it is not really about "not returning a parameter", but rather about leaving the original value of i untouched inside the function.
There's no problem with doing that and it makes it very clear what's going on.
That's one valid approach to do this, but you might also like the idea of passing by reference:
int main()
{
...
int value = 1;
Foo(value);
...
}
void Foo(int &i)
{
i = i * 2;
}
The drawback to this approach is that you have to pass what's called an lvalue into the function-- basically, something that can be on the left side of an assignment statement, which here means a variable. A call with a literal or temporary, such as Foo(2), will fail to compile. The way you had written it originally will instead do an implicit copy by value into the local scope of the Foo function. Note that the return value is now also void.
Technically, there is no problem, but semantically, it is not advisable: in most cases the input of the function and the return value of the function are not the same, so you are reusing the variable to mean something different. It is clearer in next example
int main()
{
double i = 5;
i = getSquareSurface(i); // i was a length and is now a surface
}
This should be:
int main()
{
double length = 5;
double surface = getSquareSurface(length);
}
Of course, there are cases like the addOne() or in this case the Foo() function where the meaning doesn't change.