c - How do I subtract the address of a pointer from another pointer? -


i have hw assignment write malloc in c. part of whole algorithm of freeing pointer, need subtract address of heap using bit manipulation. have following 2 declarations later defined in program.

void* heap;    metadata_t* ptr; //always < 8kb heap 

my goal take address of heap , subtract ptr because bit manipulation i'm doing works if left bit zero. i've tried far has resulted in errors. know how i'm trying?

the short answer subtraction "just works", , returns integer-type result.

#include <stdio.h>  int main(int argc, const char * argv[]) {     char string[] = "this test string";     char *a = string+8;     char *b = string+10;     long x = b-a;      printf("hello, world! , b %ld bytes apart\n", x);     return 0; } 

longer answer - if you're going a lot of arithmetic, cast pointers appropriately-large integer type, arithmetic, cast them pointer. inherently unportable, you're writing malloc, portability not high on list of concerns.

things can bit tricky, because you'll want unsigned integer type preserve of bits of pointer, doing arithmetic on unsigned types in c can annoying.


Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -