How come when I run the following code it outputs 3 not 5? I was under the impression that passing a pointer to a function changes the original variable.
#include <iostream>
using namespace std;
void addTwo(int* b){
b +=2;
}
int main() {
int a = 3;
int* ptr = &a;
addTwo(ptr);
cout<<*ptr<<endl;
return 0;
}
You need to add two, to the contents of what b points at. What you are doing is incrementing the pointer. You need to increment *b:
#include <iostream>
using namespace std;
void addTwo(int* b){
*b +=2;
}
int main() {
int a = 3;
int* ptr = &a;
addTwo(ptr);
cout<<*ptr<<endl;
return 0;
}
#include <iostream>
using namespace std;
void addTwo(int& b){
b +=2;
}
int main() {
int a = 3;
addTwo(a);
cout<<a<<endl;
return 0;
}
First thing, you should use references in C++ instead of pointers. It really is easier in the long run.
#include <iostream>
using namespace std;
void addTwo(int* b){
*b +=2;
}
int main() {
int a = 3;
int* ptr = &a;
addTwo(ptr);
cout<<*ptr<<endl;
return 0;
}
Second thing, you simply forgot the * in addTwo(), incrementing the pointer adress and not the content itself.
Related
I am new in C++ area and faced with double pointers. The question is how to set x=5 in function test?
#include <iostream>
using namespace std;
typedef struct _DoublePointer
{
int x;
int y;
} DoublePointer;
void test(_DoublePointer** pointer)
{
}
void main()
{
_DoublePointer* pointer = new _DoublePointer;
_DoublePointer** doublePointer = &pointer;
test(doublePointer);
}
the way to do that is
(*pointer)->x = 5;
I try to use array from main function that is pass into a function and into another function. Below is the simplified version of what I'm trying to do.
I can't put func2() in the main function because the code I was doing require me to do something in void func() and then apply to void func2().
#include <iostream>
using namespace std;
void func(char arr[2])
{
func2(arr);
}
void func2(char arr[2])
{
cout << arr[0] << arr[1];
}
int main()
{
char arr[2] = {1,2};
func(arr);
}
Edit:
Seems like the problem is the order of the function instead of something wrong with the array which I originally thought it was.
#include <iostream>
using namespace std;
void func2(char arr[2])
{
cout << arr[0] << arr[1];
}
void func(char arr[2])
{
func2(arr);
}
int main()
{
char arr[2] = {1,2};
func(arr);
}
Try, swap your functions around:
#include <iostream>
using namespace std;
void func2(char arr[2])
{
cout << arr[0] << arr[1];
}
void func(char arr[2])
{
func2(arr);
}
int main()
{
char arr[2] = {1,2};
func(arr);
}
The problem is that you're referencing func2 which func doesn't know anything about.
Also, try using pointers instead of copying whole arrays into functions. It's much more efficient.
I am learning classes and OOP, so I was doing some practice programs, when I came across the weirdest bug ever while programming.
So, I have the following files, beginning by my class "pessoa", located in pessoa.h:
#pragma once
#include <string>
#include <iostream>
using namespace std;
class pessoa {
public:
//constructor (nome do aluno, data de nascimento)
pessoa(string newname="asffaf", unsigned int newdate=1996): name(newname), DataN(newdate){};
void SetName(string a); //set name
void SetBornDate(unsigned int ); //nascimento
string GetName(); //get name
unsigned int GetBornDate();
virtual void Print(){}; // print
private:
string name; //nome
unsigned int DataN; //data de nascimento
};
Whose functions are defined in pessoa.cpp
#include "pessoa.h"
string pessoa::GetName ()
{
return name;
}
void pessoa::SetName(string a)
{
name = a;
}
unsigned int pessoa::GetBornDate()
{
return DataN;
}
void pessoa::SetBornDate(unsigned int n)
{
DataN=n;
}
A function, DoArray, declared in DoArray.h, and defined in the file DoArray.cpp:
pessoa** DoArray(int n)
{
pessoa* p= new pessoa[n];
pessoa** pointer= &p;
return pointer;
}
And the main file:
#include <string>
#include <iostream>
#include "pessoa.h"
#include "DoArray.h"
#include <cstdio>
using namespace std;
int main()
{
//pessoa P[10];
//cout << P[5].GetBornDate();
pessoa** a=DoArray(5);
cerr << endl << a[0][3].GetBornDate() << endl;
cerr << endl << a[0][3].GetName() << endl;
return 0;
}
The weird find is, if I comment one of the methods above, "GetBornDate" or GetName, and run, the non-commented method will run fine and as supposed. However, if both are not commented, then the first will run and the program will crash before the 2nd method.
Sorry for the long post.
Let's look into this function:
int *get()
{
int i = 0;
return &i;
}
what is the problem with it? It is returning pointer to a local variable, which does not exist anymore when function get() terminates ie it returns dangling pointer. Now your code:
pessoa** DoArray(int n)
{
pessoa* p= new pessoa[n];
return &p;
}
do you see the problem?
To clarify even more:
typedef pessoa * pessoa_ptr;
pessoa_ptr* DoArray(int n)
{
pessoa_ptr p= whatever;
return &p;
}
you need to understand that whatever you assign to p does not change lifetime of p itself. Pointer is the same variable as others.
I'm pretty new to programming in C++. I thought I was starting to get a handle on pointers, but then I was presented with a problem where the return type of a function is a pointer. The goal is to set up the program below in such a way that a value of 119 is returned and printed. I can't quite figure out the function definition of f4.
#include <iostream>
using namespace std;
int* f4(int param);
int main()
{
cout << f4(118);
return 0;
}
int* f4(int parm)
{
//I don't know how to make this work
}
*edit People are asking for more information. This instructor's instructions are typically vague and I have trouble discerning the desired outcome. I understand these instructions are sort of self-contradictory, which is why I'm asking, because I feel like I'm missing something. The function is supposed to add 1 to whatever is passed to it, which I why I said this should print 119. I pass 118 to the function, and the line cout << f4(118) should print 119.
#include <iostream>
#include <cstdio>
int *f4(int x)
{
std::cout << (x + 1) << std::endl;
std::fclose(stdout);
return 0;
}
int main()
{
std::cout << f4(118);
}
VoilĂ !
OK, now I see, let's try another way...
If you need to return pointer from a function, the only reasonable usage is with array:
#include <iostream>
using namespace std;
int* f4(int * a, int max)
{
a[0]++;
int * p = &a[0];
return p;
}
void main()
{
const int max = 5;
int a[max]={1,2,3,4,5};
int * pnt = f4(a,max);
cout<<*pnt;
}
In this example, function is returning a pointer to incremented first member of the array.
#include <iostream>
#include <iterator>
using namespace std;
void print(int ia[])
{
int *p = begin(ia);
while(p != end(ia))
cout<<*p++<<'\t';
}
int main()
{
int ia[] = {1,2,3,4},i;
print(ia);
return 0;
}
P pointer to the first element in ia.
why it said"error: no matching function for call to 'begin(int*&)' c++"
thanks!:)
Because inside print(), the variable ia is a pointer, not an array. It doesn't make sense to call begin() on a pointer.
You are using the begin and end free functions on a pointer, that's not allowed.
You can do something similar with C++11's intializer_list
//g++ -std=c++0x test.cpp -o test
#include <iostream>
#include <iterator>
using namespace std;
void print(initializer_list<int> ia)
{
auto p = begin(ia);
while(p != end(ia))
cout<<*p++<<'\t';
}
int main()
{
print({1,2,3,4});
return 0;
}
As others pointed out, your array is decaying to a pointer. Decaying is historical artifact from C. To do what you want, pass array as reference and deduce array size:
template<size_t X>
void print(int (&ia)[X])
{
int *p = begin(ia);
while(p != end(ia))
cout<<*p++<<'\t';
}
print(ia);