DojoOria -4 years ago 114
C Question

# assigning a pointer a specific memory location in C

So I'm experimenting and I'm trying to get a better understanding of how to manually place a pointer in memory in C.

So far What I've done is created a struct and assigned a pointer to it, and now I'm trying to create another struct exactly 'x' amount of memory spaces away from the first struct. for instance, if 'x' is 50 bytes, I would want both pointers to be 50 bytes away from each other.

any help would be appreciated!

edit***
I guess I left out a key point here where I used malloc() to set aside some memory to work with. and I'm trying to stay within the boundaries of that piece of memory that I've set aside. BUT i'm trying to give precise memory locations within that set aside piece of memory, relative to the starting location.

Pointers are just numbers corresponding to a memory location. You can do math on them, but it works a bit differently than normal. It's called pointer arithmetic.

Adding 1 to a pointer moves it forward in memory not 1 byte, but the size of whatever it's pointing at. If it's a `char *` it will move 1 byte. If it's a `int *` it will move 4 or 8 bytes depending on the size of your integers. If its a 50 byte struct, it will move forward 50 bytes.

So all you need to do is add 1 to your pointer.

``````#include <stdio.h>

struct example {
char string[50];
};

int main() {
struct example foo;
struct example *bar = &foo + 1;

printf("%p %p\n", &foo, bar);
}

\$ ./test
0x7fff5897b4a0 0x7fff5897b4d2
``````

...except now `bar` is pointing to unallocated memory. If you try to use it, it will be undefined behavior.

If you want to make two structs adjacent to each other in memory that you can actually use, make an array.

``````#include <stdio.h>

struct example {
char string[50];
};

int main() {
struct example list[2];

printf("%p %p\n", &list[0], &list[1]);
}

\$ ./test
0x7fff5ba21470 0x7fff5ba214a2
``````

Or if you're using heap memory...

``````#include <stdio.h>
#include <stdlib.h>

struct example {
char string[50];
};

int main() {
struct example *list = malloc( 2 * sizeof(struct example) );

printf("%p %p\n", &list[0], &list[1]);
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download