Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the address of a struct in C?

Tags:

c

memory

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*)&center);
like image 704
Nick Knowlson Avatar asked Jun 24 '12 18:06

Nick Knowlson


People also ask

How do you get an address of a struct?

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.

How do you find the address of a variable?

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.

How do you print the address of a pointer in C?

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.

What is the address of a variable in C?

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.


1 Answers

With the "address-of" operator unary &.

struct Point offCenter = { 1, 1 };
struct Point* offCentreAddress = &offCentre ;
like image 175
Clifford Avatar answered Oct 31 '22 23:10

Clifford