Write a function that will swap two integers using refrences - c++

This is a particularly strange question, but i'm attempting to write a function that swaps the values of two integers without using references or '&'. I don't see how this is even possible. Here's what I have so far.
void swap (int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
This, normally would be the way that I would do it, but since the integers don't permanently change, I have no idea as to how I would do this without referencing. Any suggestions?
Thanks!

You should correct the question title. It says “using references”. That’s the opposite of what you mean, apparently.
Assuming that:
truly no references and pointers allowed, exluding any wrapper tricks
a runtime swap is what you want – as opposed to compile time template trickery
no classes, because that would trivial
I can think of one utterly horrible solution. Make your ints globals.
ridiculous_swap.hpp
#ifndef RIDICULOUS_SWAP_HPP
#define RIDICULOUS_SWAP_HPP
extern int first;
extern int second;
void swap_ints();
#endif // RIDICULOUS_SWAP_HPP
ridiculous_swap.cpp
int first = 0;
int second = 0;
void swap_ints()
{
auto tmp = first;
first = second;
second = tmp;
}
main.cpp
#include "ridiculous_swap.hpp"
#include <iostream>
int main()
{
first = 23;
second = 42;
std::cout << "first " << first << " second " << second << "\n";
// prints: first 23 second 42
swap_ints();
std::cout << "first " << first << " second " << second << "\n";
// prints: first 42 second 23
}
It’s not useful for anything, but it does swap two integers without using references or pointers.

There is this old trick to swap two integer-like variables without using a temporary variable:
void swap(int& a, int& b)
{
a ^= b;
b ^= a; // b ^ (a ^b) = a
a ^= b; // (a ^ b) ^ a = b
}

Related

Copy constructor + Shallow & deep copy

I wanted to ask that when I don't write any copy constructor explicitly so the compiler automatically generates the copy constructor which performs shallow copy by default right?
So in the main() program when I changed the values of integers a, b and pointer p only the value of p changed and values of a and b remain unchanged in the copied object. Why the values of a & b didn't change too? My code is:
#include <iostream>
#include <string.h>
using namespace std;
class Dummy {
private:
int a, b;
int *p;
public:
Dummy() {
p = new int;
}
void setData(int x, int y, int z) {
a = x;
b = y;
*p = z;
}
void showData() {
cout << "a = " << a << " b = " << b;
cout << " p = " << *p << endl;
}
~Dummy() {
delete p;
}
};
int main() {
Dummy d1;
d1.setData(3, 4, 5);
Dummy d2 = d1;
d1.showData();
d2.showData();
d1.setData(6, 7, 8);
d1.showData();
d2.showData();
return 0;
}
The output of my program is:
a = 3 b = 4 p = 5
a = 3 b = 4 p = 5
a = 6 b = 7 p = 8
a = 3 b = 4 p = 8
What I'm saying is while the pointer of object d2 changed when I changed the values of object d1 then why didn't the values of a & b of object d2 changed too?
Also I'm using delete keyword in the destructor to delete the dynamically allocated pointer:
~Dummy() {
delete p;
}
But it's crashing my program instead. Why is that?
You've totally got it wrong - The idea of shallow copy. Actually, c++ does not have anything called deep copy built into itself. So, calling something shallow copy is a bit wrong. And just the use of these words shallow copy creates a lot of confusion too.
Now, let me explain, what happens when cpp performs initialization using assignment. cpp or c(while copying struct) has a concept called bitwise copy. In this concept, all the member variables of one object(struct object/class object - you can say either) is identically copied to another object. Now, it's totally wrong idea that, both objects point to same memory location. In actual, both object has their own memory location and of course, their variables occupy different memory spaces. For you, I have write some tests regarding memory. You would understand perfectly, if you just see the test and it's output:
#include <iostream>
#include <string.h>
using namespace std;
class Dummy {
int a, b;
int *p;
public:
Dummy() {
p = new int;
}
void setData(int x, int y, int z) {
a = x;
b = y;
*p = z;
}
void showData() {
cout << "a = " << a << " b = " << b;
cout << " p = " << *p << endl;
cout << endl; // an extra new line for readability of output
}
void showMemory() {
cout << "addr(a) = " << &a << " addr(b) = " << &b;
cout << " addr(p) = " << &p << endl;
}
~Dummy() {
*p = 100;
delete p;
}
};
// testing memory
void memoryTest() {
cout << "testing d1:" << endl;
Dummy d1;
d1.setData(3, 4, 5);
cout << "addr(d1) = " << &d1 << endl;
d1.showMemory();
cout << endl ;
cout << "testing d2:" << endl;
Dummy d2 = d1;
cout << "addr(d2) = " << &d2 << endl;
d2.showMemory();
}
int main() {
// memoryTest
memoryTest();
return 0;
}
And the output of the test was:
testing d1:
addr(d1) = 0x6dfed4
addr(a) = 0x6dfed4 addr(b) = 0x6dfed8 addr(p) = 0x6dfedc
testing d2:
addr(d2) = 0x6dfec8
addr(a) = 0x6dfec8 addr(b) = 0x6dfecc addr(p) = 0x6dfed0
This clearly shows that, the memory occupied by those two objects d1 and d2 are totally different.
Now, you may have another question remain: Then, why, when i write *p=8, it affects both d1 and d2?:
When you assign, Dummy d2 = d1;, we may say something happended like below(though, it's not actually happen when bitwise copy is applied, it's just for clarity):
d2.p = d1.p
So, we know that, d1.p and d2.p contains the same memory location(note: d1.p is a pointer. so, it does not contain any integer, rather it contains memory address of an int).
So, when you write *p = 8, you are telling the program to go to the memory location targeted by p and change the value of that memory location to 8.(note, here, you didn't change the content of d1.p, d1.p still contains the same memory location. rather, you just changed that memory location's content from 5 to 8). That's why when you call d2.p, you get the changed value. cause, d2.p contains the same memory location as d1.p.
Now, there may have one more question: Why your code crashes when you freed p in destructor?:
Now, let me first ask you, can you free a memory what is already freed. You can write the code, but the behavior is undefined. It may crashes your program or it may do nothing.
Well, in Dummy destructor you've written delete p;. Now, either d2 or d1 would be destroyed first. Let's assume, d2 is destroyed first. So, when d2's destroyer is called, p is freed. Then, d1's destroyer will be called and it'll also try to free p. But p is already freed. And in your case, the program meets a crash for this reason.
Hope, everything is clear to you now.
If anything is not clear about what I've described above, then ask questions, I will try my best to answer them too.

How to appropriately use pointers in C++ functions?

I'm trying to get the hang of pointers and addresses in C++ and am having trouble with functions with changing parameters.
The code below is writing Loop run #1. in an infinite loop, instead of incrementing the value foo.
My question is: What is the issue with this code here?
#include <iostream>
void Statement(int *foo) {
std::cout << "Loop run #" << *foo << ". ";
foo++;
}
int main() {
int foo = 1;
for (;;) {
Statement(&foo);
}
}
You're incrementing a copy of the pointer itself, not what it points to. You probably meant:
(*foo)++;
This still won't fix the infinite loop though because you have nothing to stop it with.
Your issue is that you're incrementing the pointer, not the pointed-to data.
replace
foo++
with
(*foo)++
to increment the pointed-to value.
If I have understood correctly what you are trying to do then the function should be declared the following way as it is shown in the demonstrative program
#include <iostream>
void Statement(int *foo) {
std::cout << "Loop run #" << *foo << ". ";
++*foo;
}
int main() {
int foo = 1;
for (; ; ) {
Statement(&foo);
}
}
That is in an infinite loop you are trying to output incremented value of foo.
In this case you have increment the value itself pointed to by the pointer like
++*foo
If you want to limit loop iterations then you can use for example an object of the type unsigned char and define the loop the following way
#include <iostream>
void Statement( unsigned char *foo) {
std::cout << "Loop run #" << int( *foo ) << ". ";
++*foo;
}
int main() {
unsigned char foo = 1;
for (; foo ; ) {
Statement(&foo);
}
}

Dev c++ 5.11 on Windows 8 Produces wrong answer

#include<iostream>
#include<conio.h>
class Number
{
private:
int x, y;
public:
Number()
{
x = y = 100;
}
void avg()
{
std::cout<<"x = "<<std::cout<<x;
std::cout<<std::endl;
std::cout<<"Y = "<<std::cout<<y;
std::cout<<std::endl;
std::cout<<"Average = "<<std::cout<<(x+y)/2;
}
};
main()
{
Number n;
n.avg();
}
This programme runs but shows wrong answer, may be showing addresses of memory locations instead of showing the assigned values of 100. Please correct me why it is behaving like this?
std::cout << "x = " << std::cout << x;
is wrong. You need
std::cout << "x = " << x;
Otherwise, the std::cout stream object in ...<< std::cout is implicitly converted to a (void*) when invoking operator<< on it, and therefore the pointer (an address) is displayed.
The conversion to void* exists for historic reasons (the safe bool idiom), but in C++11 was removed, due to the introduction of explicit conversion operators, so your code should not compile in C++11.

Pointers structures and dynamic memory allocation in c++

I have two structures in which the second structure has the first structure nested inside of it:
struct first
{
int a;
};
struct second
{
first nested;
};
Now the problem is that the second structure has to be dynamically allocated through a pointer. Also, the nested first structure has to be a dynamically allocated array through a pointer, whose array size has to be read in through an input file.
I know how to read it in but I don't know how to access it. For example lets suppose the size is 8. How would I go about specifying the values for the second structure given the pointer's format?
I tried assuming ptr points to first structure and ptr1 points to second structure ptr1->((ptr+count)->a) where we can process it through a loop. This doesn't work. So I was wondering how you would initialize the values the second structure whose member includes all the n structures in the n element array.
Vector is really easy just stick your struct where type is and use it like any other array. Although what you described really sounds like linked list but hey vector will probably be better for you :)
#include <vector>
//main
vector <Type> myArray(8); //set the number of elements you want
myArray[0] = blablabla
More specific example:
struct first
{
int a;
};
vector <first> myArray(8);
first[0].a = 1; // you get the idea :)
EDIT
From the comments this seems to me more up your alley.
struct bla {
int num;
};
//in main
bla *balBla = NULL;
blaBla = new(bla[8]); //There made on the fly dynamic man
blaBla[0].num = 7;
//Don't forget to delete when done or scary memory leak!!!
delete[] blaBla;
Last Edit If this is not what you want then no one will ever understand what you mean
#include <iostream>
using namespace std;
struct b {
int num;
};
struct a {
b *nested = NULL;
a(){} //Default Constructor
a(int elements) {
nested = new(b[elements]);
} //Lets you add elements to nested at initialization
void addElem(int elements) {
if (nested != NULL) {
delete[] nested;
}
nested = new(b[elements]);
} //Redefine or make new array
~a() {
delete[] nested;
} //destructor
};
int main() {
a myStupidObj(3);
myStupidObj.nested[0].num = 69;
myStupidObj.nested[1].num = 77;
myStupidObj.nested[2].num = 666;
cout << "Struct of one D array of structs" << endl;
cout << myStupidObj.nested[0].num << endl;
cout << myStupidObj.nested[1].num << endl;
cout << myStupidObj.nested[2].num << endl;
//Make 2d version
a *my2DStupidObj = new(a[2]);
my2DStupidObj[0].addElem(3);
my2DStupidObj[0].nested[0].num = 666;
my2DStupidObj[0].nested[1].num = 6969;
my2DStupidObj[0].nested[2].num = 80085;
cout << "array of struct of one D array of structs" << endl;
cout << my2DStupidObj[0].nested[0].num << endl;
cout << my2DStupidObj[0].nested[1].num << endl;
cout << my2DStupidObj[0].nested[2].num << endl;
my2DStupidObj[1].addElem(3);
my2DStupidObj[1].nested[0].num = 11;
my2DStupidObj[1].nested[1].num = 111;
my2DStupidObj[1].nested[2].num = 1111;
cout << my2DStupidObj[1].nested[0].num << endl;
cout << my2DStupidObj[1].nested[1].num << endl;
cout << my2DStupidObj[1].nested[2].num << endl;
delete [] my2DStupidObj;
return 0;
}
In C, you sometimes see something like:
struct second {
int count;
first nested[1];
};
Then, you allocate memory. The amount you allocate is computed as sizeof(struct second) plus the size of first times the number of elements you want in the array minus 1 (since there is already one included).
ptr = (struct second *)malloc(sizeof(struct second) + ((n-1) * sizeof(first)));
Then you can use
ptr->nested[idx].a
or if you have to use pointers,
((ptr->nested)+idx)->a
Of course, you have to do all the housework and cleanup yourself. C++ and its std libraries do most of that for you.

How to put constants in code memory

I need to keep some information about each function in my program in the form of a constant number. I was wondering if it is possible to put the constant for a function just before it in the code memory, so if a function is called through a function pointer, that information could be read by subtracting the value of the function pointer.
To illustrate further, my code memory should look as follows.
ConstantForFunc1
Func1:
....
ConstantForFunc2
Func2:
....
And following is an example code of how I would read that information
FuncPointer f = &Func2;
int constantForFunc2 = *((int*)(f - sizeof(int)));
And note that using Hash tables is too slow for what I'm trying to achieve, so I need a very fast method. And all this modification, which is inserting constants and code to read from them is done by a compiler pass, which I'm writing and which modifies the LLVM IR. Using structures would be too cumbersome for the compiler pass, as it would have to modify a lot of code.
What you are doing doesn't make sense, yet:
You could use structs maybe?
struct example
{
int constantForFunc;
void (*ptrToFunc)();
};
//After declaring, maybe 3, functions
struct example funcList[3] = {{5, &func1}, {10, &func2}, {15, &func3}};
int currentFuncConstant=funcList[1].constantForFunc;
(*funcList[1].ptrToFunc)();
I haven't used function pointers to be honest, probaby has mistakes.
Is this not acceptable at all?:
#include <iostream>
using namespace std;
const int Const__Fxn1 = 1;
void Fxn1()
{
cout << "Fxn1" << endl;
}
const int Const__Fxn2 = 2;
void Fxn2()
{
cout << "Fxn2" << endl;
}
#define GetFxnConst(FxnName) Const__ ## FxnName
int main()
{
cout << GetFxnConst(Fxn1) << endl;
cout << GetFxnConst(Fxn2) << endl;
return 0;
}
Option 2:
#include <iostream>
#include <cstring>
using namespace std;
const volatile int v1 = 0;
volatile unsigned v2 = 0;
void Fxn1()
{
if (v1) { v2 = 0x12345601; }
cout << "Fxn1" << endl;
}
void Fxn2()
{
if (v1) { v2 = 0x12345602; }
cout << "Fxn2" << endl;
}
int FindFxnConst(void(*f)())
{
const unsigned char* p = (const unsigned char*)f;
while (memcmp(p, "\x56\x34\x12", 3))
p++;
return p[-1];
}
int main()
{
Fxn1();
cout << FindFxnConst(Fxn1) << endl;
Fxn2();
cout << FindFxnConst(Fxn2) << endl;
return 0;
}
Output (Ideone):
Fxn1
1
Fxn2
2
You can embed more than 8 bits of data per function by using other magic prefixes, e.g.:
if (v1)
{
v2 = 0x12345611; // byte 1
v2 = 0x789ABC22; // byte 2
v2 = 0xDEF01233; // byte 3
v2 = 0xFEDCBA44; // byte 4
}
This is not necessarily a reliable solution, let alone portable.
Since the addresses of the functions are known from the executable binary (unless they are loaded from a shared library ofcourse), if you have the address space layout randomization (ASLR) off, you could use gperf to generate a highly efficient hash function for you and use that hash function to get the constants for each function.
However, for this, you will have to compile your program twice, first to get the addresses of the functions from the generated binary, so that you could give those addresses as an input to gperf and recompile using the hash function generated by gperf. But you have to be careful that the addresses of the functions from the first compilation do not become different in the second compilation. I am not sure, how to achieve that.
An alternative, would be to do something like gperf just after your program is loaded, so you don't have to compile twice. But I don't know how to do that.