1
char mening[] = "tjena pa dig hog";

This string contains 16 characters. I am then using a function adresss() to find the memory address of a random character in that array. The function adresss() returns a pointer containing the address. The address is at this moment 0x7ffeefbff5f9. I now need to know what positions that address is pointing to, example is it pointing to the "t" at position 0 in the array, or maybe it is pointing to "d" at position 9. How do I do this?

Edit:

char* adresss(char mening[]){

   //Lots of code going on here

   return &mening[i];
}

int main(void){
   char mening[] = "tjena pa dig hog";
   char* ptr;
   ptr = adresss(mening);

   printf("%p\n", ptr);

That is basically how I get the memory adress. I want to know what "i" was, inside the main function only knowing the memory adress.

5
  • The adresss() function is returning like this: return &mening[i]; that will give the adress of position i in mening[] I want to find i again using only the memory adress Commented Feb 19, 2018 at 16:21
  • While the number of elements of the array mening is 16, remember that the last one (with index 15) is the string terminator. Commented Feb 19, 2018 at 16:25
  • @Someprogrammerdude.: The array has size 17 and index 15 is g. Commented Feb 19, 2018 at 16:37
  • I want to find the index of the array from the given adress Commented Feb 19, 2018 at 16:38
  • 1
    @coderredoc Details shmetails... :) Commented Feb 19, 2018 at 18:11

1 Answer 1

1

If you have two pointers, both pointing to the same array (or to one beyond the end of the array), then you can subtract them from each other.

For example:

char mening[] = "tjena pa dig hog";
char *pointer_to_mening = &mening[10];  // Pointer to the eleventh character

// Should print 10 (which is the index of the eleventh character)
printf("The distance is %zu\n", pointer_to_mening - mening);
Sign up to request clarification or add additional context in comments.

2 Comments

What does %zu mean?
@J.Doe "%u" is to print an unsigned int. The z modifier is for size_t arguments. That means "%zu" prints a size_t argument as an unsigned integer. See e.g. this printf (and family) reference for more details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.