accessing structure nodes in C

I'm new on StackOverflow so sorry if this topic was already discussed.

I'm working on a project, and I need to use the minimum amount of memory, so my question is: is it possible to access the adres of node of a structure by having the adress of a field of this structure. For example I have this structure:

typedef struct SLL{
    char *name;
    int *id;
    struct SLL *next;
    }SLL;

somewhere in my code I obtain the adress of id... so it is possible to get the adress of whole node by using adress of id?

Answers


Consider offsetof <stddef.h>:

typedef struct SLL{
    char *name;
    int *id;
    struct SLL *next;
    }SLL;

int main()
{
   SLL *p=malloc( sizeof(SLL));
   void *id=&p->id;
   void *test= id - offsetof(SLL, id);
   printf("SLL=%p  test=%p\n", p, test);
   return 0;

}    

Yes you can because the structure is stored contiguously. Your question pertains to pointer arithmetic. The address of the whole node (value of structure pointer) is (SLL*)(id - sizeof (name)).


Typically, the address of the struct is the same as the address of the first member.

This is compiler dependent however (I think. Don't quote me on this. Seriously.), and you may have padding bytes added to the struct for reasons I do not understand but could hopefully take note of if a more experienced person is to comment on this explaining why :V

Your best bet is subtracting sizeof(char*) from the memory address of (int* id).


YES you can get it. As soon as you will give a memory to this structure, a memory block will get reserve for this.That block will have contiguous memory lcation for three pointers which are char ,int and SLL type.if you are knowing pointer to second element then just substract sizeof(char*) from this, to reach the base location(or first element) of this structure.


Need Your Help

Parsing Email(Email format is not Fixed) for certain fields in c#

c# email

We have a requirement to Parse the email and get certain fields like Name, Address and from email address from the mail body and Header. The Problem lies in the fact that the format of email is not...

Is there any example about Spanned and Spannable text

android android-widget

I'm struggling with using EditText and Spannable text object, These days, I've read API documents around ten times, even I'm not certain that I understand correctly. So I'm looking for a kind of ex...