Skip to content

Instantly share code, notes, and snippets.

@bbarker
Last active August 29, 2015 14:24
Show Gist options
  • Save bbarker/5dd93bd808898205d60c to your computer and use it in GitHub Desktop.
Save bbarker/5dd93bd808898205d60c to your computer and use it in GitHub Desktop.
Experiments with const in C
#include <malloc.h>
#define ARRSZ 10
int main() {
int x = 5;
const int* xp = &x;
int y = 5;
int* yp = &y;
//*xp = 6; // error: assignment of read-only location '*xp'
x = 6; // ...but OK to assign a new value this way
*yp = 6;
printf("x = %1d, y = %1d\n",*xp,*yp);
// But we can still change the values directly!
x = 4;
y = 4;
int x1 = 7;
int y1 = 7;
xp = &x1; // reassigning pointers is OK
yp = &y1;
xp = malloc(ARRSZ * sizeof x); // again, OK
yp = malloc(ARRSZ * sizeof y);
// *xp = 6; // error: assignment of read-only location '*xp'
*yp = 6;
// Seems we can't write to ANY location relative to pointer xp,
// even though we are no longer pointing to the same memory
// *(xp+1) = 6; // Can't write here either!
*(yp+1) = 6;
// Now, what if we define an int* pointer to the same location?
int* xncp = (int*) xp; // OK! (the cast avoids a warning)
*xncp = 8;
printf("*xp = %1d, *xncp = %1d\n",*xp,*xncp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment