Home > Mobile >  How Do I Interpret the Following Lines of Code
How Do I Interpret the Following Lines of Code

Time:03-04

typedef struct {
int a;
short s[2];
} MSG;
MSG *mp, m = {4, 1, 0};
char *fp, *tp;
mp = (MSG *) malloc(sizeof(MSG));
for (fp = (char *)m.s, tp = (char *)mp->s; tp < (char *)(mp 1);)
*tp   = *fp  ;

so i've sussed out from my memory of c programming that the first block is a structure declaration using typedef to define an alias. The alias is MSG? Next pointer *mp, and struct m = {4, 1, 0} are declared as type MSG. Next two char pointers are created, *fp and *tp. mp is set equal to malloc(sizeof(MSG)) which is cast to type (MSG *) or type pointer to MSG?. Next a for loop is set where for fp = the m.s (the s within struct m so to speak) is cast to a pointer to a char, tp = pointer mp set to struct s; and tp < (char *)(mp 1) or pointer plus 1);)

I'm just really unsure as my memory of c is quite foggy at this point. Could someone correct me or better articulate exactly what this code is doing? I'm trying to discern whether or not I'm ready to start studying a certain book and this is the first block of code. Next whatever pointer fp points to is incremented set to *tp which is also incremented.

CodePudding user response:

Converting comments into an answer.

  • Yes; MSG is the alias.
  • Yes, mp is an uninitialized pointer and m is an initialized MSG structure.
  • Yes, fp and tp are char * variables.
  • The cast isn't necessary in C, but is in C .
  • The code then writes out memcpy() — more or less.

It could be written:

memmove(mp->s, m.s, sizeof(m.s));

(or you could use memcpy() — I don't use that, though). The (char *)(mp 1) limit on the loop is the start of the structure after the allocated structure.

The code could also be written as:

mp->s[0] = m.s[0];
mp->s[1] = m.s[1];

which might even be faster still. In fact, it could simply be written as:

*mp = m;

which does initialize mp->a but that shouldn't be left uninitialized for long anyway. If the m structure isn't used again, then the code could eliminate the variable and write:

*mp = (MSG){ .a = 4, .s = { 1, 0 } };

using a compound literal and designated initializers, both of which require support for C99 or later.

There are a lot of ways to improve that code snippet. It leaves one wondering whether that is a good book to be learning from. It might be worth keeping a sceptical eye open for infelicities in the book. If it was written in the mid-oughts (200x) or in the last millennium, then there are better excuses for what was written, but is a book that old worth reading? (There are some books of that era that are still worth reading — see comments below.)

  • Related