This question already has answers here:
What are the differences between a pointer variable and a reference variable?
(44 answers)
Closed 1 year ago.
i'm code beginner
#include <bits/stdc++.h>
using namespace std;
void init(int* arr){
arr = new int[10];
cout << arr << endl;
}
int main(int argc, char* argv[]){
int *arr;
init(arr);
cout << arr << endl;
}
this is a simple code.
My question is that why arr's address in init function and arr's address in main function is different?
My think is that i gave arr's address to init function and in init function, arr is assigned a new address through 'new int[10]'
So, arr's address in init function and in main will be same.
but this code doesn't work as i think.....
Can you tell me why?
Step back a little and think about how arguments are passed into functions.
void foo(int x) {
}
int main() {
int x;
foo(x);
}
Here the x in main() is actually passed by value to foo() which means a copy of x is created when passing to foo().
With the same logic, if you think of int * as another variable type
using intPtr = int*; //a sort of typedef
void foo(intPtr x) {
}
int main() {
intPtr x;
foo(x);
}
a copy of x is again created. This is what is happening in your program. For what you expect, you need to pass in the variable by reference
using intPtr = int*;
void foo(intPtr& x) {
}
int main() {
intPtr x;
foo(x);
}
Adapting the same to your program:
#include <iostream>
void init(int*& arr){
arr = new int[10];
std::cout << arr << '\n';
}
int main(int argc, char* argv[]){
int *arr;
init(arr);
std::cout << arr << '\n';
delete(arr);
}
There's another way with pointers that is using a pointer to a pointer (**)
#include <iostream>
void init(int** parr){
*parr = new int[10];
std::cout << *parr << '\n';
}
int main(int argc, char* argv[]){
int *arr;
init(&arr);
std::cout << arr << '\n';
delete(arr);
}
where the address of arr (&arr) is passed into the function. Inside the function, the contents of parr is modified (which is arr in this case).
Related
This question already has answers here:
What is a dangling pointer?
(7 answers)
Closed 12 days ago.
I am trying to swap a pointer to point to the address of a new class instance created inside a method, but once back to main, the reference is lost, is this because of scope? Could someone please care to explain? Does c/c++ have reference counting?
#include <iostream>
class MyClass {
public:
int myNum;
std::string myString;
MyClass(int my_num, std::string my_string)
{
myNum = my_num;
myString = my_string;
}
};
void SwapRef(MyClass **p)
{
MyClass b(99, "test");
*p = &b;
}
int main(int argc, char* argv[])
{
MyClass a(1, "main");
MyClass* aPtr = (MyClass*)0;
aPtr = &a;
std::cout << "myNum is: " << aPtr->myNum << " myString is: " << aPtr->myString << "\n";
SwapRef(&aPtr);
std::cout << "myNum is: " << aPtr->myNum << " myString is: " << aPtr->myString << "\n";
#ifdef _WIN32 || _WIN64
system("pause");
#endif
}
OUTPUT:
myNum is: 1 myString is: main
myNum is: -858993460 myString is:
This function
void SwapRef(MyClass **p)
{
MyClass b(99, "test");
*p = &b;
}
is wrong. The object b having automatic storage duration will not be alive after exiting the function. So the pointer aPtr assigned in the function with the address of the local object using the expression statement
*p = &b;
will be invalid after exiting the function.
Dereferencing such a pointer invokes undefined behavior.
Instead you could write
**p = b;
using the generated by the compiler the default copy assignment operator.
The function could be correct if the object declared within the function would have static storage duration like
void SwapRef(MyClass **p)
{
static MyClass b(99, "test");
*p = &b;
}
In this case it will be alive after exiting the function.
Pay attention to that you should include header <string>
#include <string>
because it is not necessary that the header <iostream> includes the header <string>.
#include <iostream>
using namespace std;
void b();
int main() {
int a = 10;
b();
}
void b() {
int a;
cout<<"Int a="<<a;
}
I am looking to print the value of a in the main scope using a function, with my current code, it prints Int a=0. How can I achieve this?
Don't declare an entirely new a inside b().
Pass the a from main to b() and then print that.
For example:
#include <iostream>
void b(int whatever_name_you_want_here);
int main()
{
int a = 10;
b(a);
}
void b(int whatever_name_you_want_here)
{
std::cout << "Int a=" << whatever_name_you_want_here;
}
//Change your code to the following and it will give you the result you're looking for.
On your code there is no way to pass int a on the main to b(); unless b accepts a parameter of the type you want the function to output.
#include<iostream>
void b(int);
int main()
{
int a = 10;
b(a);
}
void b(int a){
std::cout << "int a=" << a;
}
I guess the main problem is not being aware of something very important which is called scope! Scopes are usually opened by { and closed by }
unless you create a global variable, it is only known inside the scope it has been introduced (declared).
you declared the function b in global scope :
void b();
so after this every other function including main is aware of it and can use it.
but you declared the variable a inside the scope of main:
int a = 5;
so only main knows it and can use it.
Please make note that unlike some other programming languages, names are not unique and not every part of the program recognize them in c and c++.
So the part:
void b() {
int a;
does not force the function b to recognize the a which was declared in main function and it is a new a.
so to correct this mistake simply give the value or reference of variable a to function b :
#include <iostream>
void b(int&);
int main() {
int a = 10;
b(a);
}
void b(int& a) {
std::cout << "Int a=" << a << std::endl;
}
please also note that the a as argument of the function b is not the same a in the function main.
The final tip is every argument for functions is known inside that function scope as it was declared inside the function scope!
What you want to achieve requires you to pass a value to a function. Let me give you an example on how to do that.
#include<iostream>
void print_value(int value){
std::cout << "Value is: " << value << '\n';
}
int main(){
int a = 5;
print_value(a);
return 0;
}
The only thing you are missing in your program is the parameter. I won't bother explaining the whole thing over here as there are numerous articles online. Here is a straightforward one.
Refer to this to understand how functions work in C++
Use pass by reference to access a variable which is declared in one function in another.
Refer the below code to understand the use of reference variable,
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "\n";
cout << firstNum << secondNum << "\n";
// Call the function, which will change the values of firstNum and secondNum
swapNums(firstNum, secondNum);
cout << "After swap: " << "\n";
cout << firstNum << secondNum << "\n";
return 0;
}
#include <iostream>
using namespace std;
void displayValue(int number) {
cout<<"Number is = "<<number;
}
int main()
{
int myValue = 77;
displayValue(myValue);
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int *p;
*p=9;
cout<<*p<<endl;
return 0;
}
Why is this code not executing in devc++?
You never allocated any memory for p so you have an uninitialized pointer pointing to garbage. Once you dereference it is undefined behavior.
int *p;
Should be
int *p = new int;
And then you need a
delete p;
before the end of main as every new/new[] should be matched with a delete/delete[].
But in this case there is no reason to even do that. Just use a regular int and you have
int main()
{
int p = 9;
std::cout<< p << '\n';
return 0;
}
I have this struct:
struct noduri {
int nod[100];
};
and this function:
int clearMatrix(int var)
{
cout << all[1].nod[30];
}
int main()
{
noduri all[100];
cout << all[1].nod[30];
return 0;
}
and I want the struct to be assigned to all 100 elements of array all[], when I do cout << all[1].nod[30]; everything works fine, no errors, it outputs 0. When I call clearMatrix(1) I get this error : error: request for member nod in all[1], which is of non-class type int, what am I doing wrong ?!
The array variable all is local to the main function, so you cannot reference it in clearMatrix unless you pass a pointer to it into the function:
int clearMatrix(int var, noduri *all)
{
cout<<all[1].nod[30];
}
int main()
{
noduri all[100];
clearMatrix(5, all);
return 0;
}
you are reffering in the function that array which is not in its scope, you need to do it as
int clearMatrix(int var,noduri *all)
{
cout<<all[1].nod[30]; // as here you have the base address of the array of type noduri you can refer it.
}
int main()
{
noduri all[100];
clearMatrix(5, all);
return 0;
}
You are using raw arrays. That's not a good idea. Use std::vector if the size if not known at compile time, consider std::array if it is known at compile time and dynamic resizing would cause measurable performance problems.
One of the problems with raw arrays in C++ is that it's not at all(!) as easy to pass them to a function like, say, an int or a double. std::vector and std::array, in contrast, are as easy to pass to a function like any other normal type.
Here's a complete example:
#include <array>
#include <iostream>
struct noduri {
std::array<int, 100> nod;
};
void clearMatrix(std::array<noduri, 100> const &array) {
std::cout << array[1].nod[30];
}
int main() {
std::array<noduri, 100> all;
std::cout << all[1].nod[30];
}
Note that std::array is only available if your compiler supports C++11. For an older compiler, use boost::array or just do it with a std::vector.
The code you showed will not be compiled and has no any sense. If I have understood correctly you want to assign each element of the array by some value in function clearMatrix. If so then the code will look the following way
#include <iostream>
struct noduri
{
int nod[100];
};
int clearMatrix( noduri *matrix, int size, int var )
{
for ( int i = 0; i < size; i++ )
{
for ( int &n : matrix[i].nod ) n = var;
}
}
int main()
{
const int N = 100;
noduri all[N] = {};
std::cout << all[1].nod[30] << std::endl;
clearMatrix( all, N, 10 );
std::cout << all[1].nod[30] << std::endl;
return 0;
}
#include "stdafx.h"
#include <iostream>
using namespace std;
class thing{
public:
int stuff, stuff1, stuff2;
void thingy(int stuff, int *stuff1){
stuff2=stuff-*stuff1;
}
}
int main(){
thing t;
int *ptr=t.stuff1;
t.thingy(t.stuff, *ptr);
}
I've been practicing classes, and pointers in C++. What i'm trying to do is have the function thingy modify the stuff2 data member in the thing class by passing a pointer to the value of stuff1. How do I go about doing this?
You are creating a variable of type pointer-to-int: if you want a pointer to t.stuff1, take its address:
int* ptr = &t.stuff1;
___^ here you are taking a reference (address)
Then, pass that pointer to your thing::thingy method:
t.thingy(t.stuff, ptr);
__^ don't dereference the pointer, your function takes a pointer
Try this:
int *ptr;
*ptr = t.stuff1;
t.thingy( t.stuff, ptr);
Im probably really late to the party but i wanted to get some good comments and test
//#include "stdafx.h"
#include <iostream>
using namespace std;
//class declaration
class thing{
public:
int stuff, stuff1, stuff2;
thing(){//constructor to set default values
stuff = stuff1 = stuff2 = 10;
}
void thingy(int param1, int *param2){
stuff2=param1-*param2;
}
};
//driver function
int main(){
thing t;//initialize class
cout << t.stuff << ' ' << t.stuff1 << ' ' << t.stuff2 << endl;//confirm default values
int *ptr= &t.stuff1;//set the ADDRESS (&) of stuff1 to an int pointer
cout << *ptr << endl;
t.thingy(t.stuff, ptr); //call function with pointer as variable
cout << t.stuff1;
}
int *ptr=t.stuff1;
you cannot convert int to int*
t.stuff1 is an int value, not a pointer of int
try this:
int *ptr=&t.stuff1;
and you should add ";" at the end of the define of class, like this:
class Thing {
...
};
and when you call t.thingy, the second param is int*
But *ptr is an int value, not a pointer. ptr is a pointer, not *ptr. try this:
t.thingy(t.stuff, ptr);
you should know:
int i_value = 1;
int* p_i = &i_value;
int j_value = *p_i;
in this case:
the type of i_value j_value *p_i is int
the type of p_i is int*
You should pass the address:
*ptr = &(t.stuff1);