Skip to content

Instantly share code, notes, and snippets.

@mikehelmick
Created February 13, 2014 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikehelmick/8977291 to your computer and use it in GitHub Desktop.
Save mikehelmick/8977291 to your computer and use it in GitHub Desktop.
Modifying the contents of a const array
#include <iostream>
using namespace std;
void printArray(int a[], int size) {
for (int i = 0; i < size; i++) {
cout << a[i] << " ";
}
cout << endl;
}
void modifyConstArray(const int a[], int size) {
// Casualy interpret the address of the const array as an int
int x = (int) a;
// Re-interpret that int as a pointer
int* y = (int*) x;
// You can now easily change memory passed to you as const. Easy as pie.
for (int i = 0; i < size; i++) {
y[i] = -1;
}
}
int main() {
int size = 10;
int arr[size];
for (int i = 0; i < size; i++) {
arr[i] = i;
}
printArray(arr, size);
modifyConstArray(arr, size);
printArray(arr, size);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment