I was wondering if there is a way I can store a NULL value or an address at an address relative to a pointer by using pointer arithmetic in C.
int *p;
p = NULL; // is possible
int *p, *q;
p + 1 = NULL; // ERROR: lvalue required as left operand of assignment
p + 1 = q; // ERROR: lvalue required as left operand of assignment
You would need to do something like this, assuming p
points to a valid piece of memory that you have rights to writing to:
int **p = something;
p[1] = NULL;
p[1] = q;
It isn't exactly clear to me what you are asking. You can set a pointer to a NULL value and you can point to a value that is NULL. You cannot set a pointer to NULL then attempt to use it as a target for a value. Here is an example of using pointer arithmetic
int *p = (int*) malloc(3 * sizeof(int));
*p = 0; // dereference p and set it's value to 0
*(p + 1) = 1; // add 1 sizeof(int) to p and set it's value to 1
NULL is just an alias for 0.
int *p, *q;
*(unsigned int *)(p + 1) = (intptr_t)NULL;
// or
*(unsigned int *)(p + 1) = (intptr_t)q;
This seemed to work for me.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.