I'm an absolute newbie to C so this may be a dumb question, warning!
It's inspired by the extra credit section of Exercise 16 in Learn C the Hard Way, if anyone is wondering about context.
Assuming these imports:
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
And given a simple struct like this:
struct Point {
int x;
int y;
};
If I create an instance of it on the heap:
struct Point *center = malloc(sizeof(Point));
assert(center != NULL);
center->x = 0;
center->y = 0;
Then I know I can print the location of the struct in memory like this:
printf("Location: %p\n", (void*)center);
But what if I create it on the stack?
struct Point offCenter = { 1, 1 };
Values sitting in the stack still have a location in memory somewhere. So how do I get at that information? Do I need to create a pointer to my new on-the-stack-struct and then use that?
EDIT: Whoops, guess that was a bit of an obvious one. Thanks to Daniel and Clifford! For completeness here's the print example using &
:
printf("Location: %p\n", (void*)¢er);
In C, we can get the memory address of any variable or member field (of struct). To do so, we use the address of (&) operator, the %p specifier to print it and a casting of (void*) on the address. Note: We have used & before opengenus to get the address in form of a pointer.
To access address of a variable to a pointer, we use the unary operator & (ampersand) that returns the address of that variable. For example &x gives us address of variable x.
You can print a pointer value using printf with the %p format specifier. To do so, you should convert the pointer to type void * first using a cast (see below for void * pointers), although on machines that don't have different representations for different pointer types, this may not be necessary.
An address is a non-negative integer. Each time a program is run the variables may or may not be located in same memory locations. Each time you run the program above may or may not result in the same output.
With the "address-of" operator unary &
.
struct Point offCenter = { 1, 1 };
struct Point* offCentreAddress = &offCentre ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With