How can I get the structure address in C?

I am absolutely new to C, so this might be a dumb question, warning!

This inspired the optional lending section of Exercise 16 in the β€œLearn C the Hard Way” if someone wonders about the context.

Assuming import:

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

And given the simple structure:

 struct Point { int x; int y; }; 

If I instantiate it on the heap:

 struct Point *center = malloc(sizeof(Point)); assert(center != NULL); center->x = 0; center->y = 0; 

Then I know that I can print the location of the structure in memory as follows:

 printf("Location: %p\n", (void*)center); 

But what if I create it on the stack?

 struct Point offCenter = { 1, 1 }; 

Values ​​on the stack still have a place in memory. So how do I get this information? Do I need to create a pointer to my new on-the-stack structure and then use this?

EDIT: Oops, suppose this was a little obvious. Thanks to Daniel and Clifford! For completeness, here is an example of printing using & :

 printf("Location: %p\n", (void*)&center); 
+7
source share
1 answer

With the address-of operator unary & .

 struct Point offCenter = { 1, 1 }; struct Point* offCentreAddress = &offCentre ; 
+11
source

All Articles