Accessing Strings vs ints in a structure

Q&A's, tips, howto's
Locked
lwix
Posts: 24
Joined: Tue Oct 26, 2004 3:14 am
Location: New Zealand

Accessing Strings vs ints in a structure

Post by lwix »

In the manual we have this example:
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
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

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) => "A\000\000\000"
(get-integer "A\000\000\000") => 65

Lutz

lwix
Posts: 24
Joined: Tue Oct 26, 2004 3:14 am
Location: New Zealand

Post by lwix »

Yep, makes perfect sense. Thanks.
small's beautiful

Locked