Created
October 19, 2021 20:21
-
-
Save apetenchea/8f10b1d1cbf73fa27b702ad30955931d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example of a constant being modified | |
// clang++ -Wall -std=c++17 -O2 -o modify_const modify_const.cpp | |
#include <iostream> | |
#include <string> | |
#include <sstream> | |
unsigned long long hex_to_dec(std::string str) | |
{ | |
unsigned long long result = 0; | |
unsigned long long power = 1; | |
for (int index = str.length() - 1; index > 1; --index) { | |
int c = str.at(index); | |
c -= std::isdigit(c) ? '0' : 'a' - 10; | |
result += c * power; | |
power *= 16; | |
} | |
return result; | |
} | |
int main() | |
{ | |
const int x[] = {1, 2, 3}; | |
std::cout << "Initial value of x[0] " << *x << '\n'; | |
const int* ptr = x; | |
std::stringstream strm; | |
strm << ptr; | |
auto s = strm.str(); | |
unsigned long long result = hex_to_dec(s); | |
int* y = (int*) result; | |
std::cout << "Initial value of *y " << *y << '\n'; | |
*y = 1234; | |
std::cout << "New value of *y " << *y << '\n'; | |
std::cout << "Addr x and y " << x << ' ' << y << '\n'; | |
std::cout << "New value of x[0] " << *x << '\n'; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment