Accessing Strings vs ints in a structure

Started by lwix, November 14, 2004, 05:27:19 PM

Previous topic - Next topic

lwix

In the manual we have this example:
Quote
typedef struct mystruc {

    int number;

    char * ptr;

    } MYSTRUC;

 

 MYSTRUC * foo3(char * ptr, int num )

    {

    MYSTRUC * astruc;

 

    astruc = malloc(sizeof(MYSTRUC));

    astruc->ptr = malloc(strlen(ptr) + 1);

    strcpy(astruc->ptr, ptr);

    astruc->number = num;

 

    return(astruc);

    }

 

 > (set 'astruc (foo3 "hello world" 123))

 4054280

 > (get-string (get-integer (+ astruc 4)))  <--- ??

 "hello world"

 > (get-integer astruc)

 123


Assuming that astruc is just a memory address, why do we need to call 'get-integer' before we get at the string?



I redefined the struct so that the char* came before the int and noticed that we still need to use 'get-integer' before 'get-string'. But getting the integer is still straightforward: (get-integer (+ astruc 4))
small\'s beautiful

Lutz

#1
My previous answer to your question was wrong and I have deleted that post.



This is why the 'get-integer' in:



(get-string (get-integer (+ astruc 4)))



is necessary. 'astruc' is the address of the data structure returned. 4 bytes into the structure is a 'char *' which is another address, this time to a string buffer. So:



(+ astruc 4) = > address where address pointer can be found

(get-integer (+ astruc 4)) => address of string buffer



There is a relation between 'pack' and 'get-integer' which also makes it clear:



(pack "ld" 65) => "A000000"

(get-integer  "A000000") => 65



Lutz

lwix

#2
Yep, makes perfect sense. Thanks.
small\'s beautiful