user2885778
user2885778

Reputation: 65

type of pointer difference (minus)

I need to know the memory distance between two substructures

(&my_type.a - &my_tape.b.c)

What is the type of the result? I need to cast it to (signed int), so obviously it's something else.

Upvotes: 1

Views: 428

Answers (3)

Eric Postpischil
Eric Postpischil

Reputation: 222734

First, you cannot take the addresses of members of types. If my_type is a type name, then &my_type.a is not a valid expression. You first need an object of the type. E.g., you could use my_type foo; (&foo.a - &foo.b.c).

Second, if a and c are not character types, then the result of &foo.a - &foo.b.c is not defined by the C standard, even if they are the same type as each other. The C standard defines the result of subtracting pointers only if they are pointers to elements in the same array object or one past the last element of the array object. (For this purpose, a single element behaves as an array of one element.)

You can obtain a defined result by converting the pointers to a character type:

my_type foo;
(char *) &foo.a - (char *) &foo.b.c

The result of this expression has type ptrdiff_t. It is defined because the entire object foo may be treated as an array of char, so pointers to bytes within it may be subtracted.

Upvotes: 0

Potatoswatter
Potatoswatter

Reputation: 137810

According to the C11 standard, §6.5.6/9,

When two pointers are subtracted… The size of the result is implementation-defined, and its type (a signed integer type) is ptrdiff_t defined in the <stddef.h> header.

Upvotes: 6

Antzi
Antzi

Reputation: 13424

You can use a size_t for that (which is often unsigned int) If you need it signed use ssize_t see What is size_t in C?

Edit: You probably should use ptrdiff_t for that see http://www.viva64.com/en/a/0050/

Upvotes: 1

Related Questions