Path: utzoo!utgpu!water!watmath!clyde!rutgers!umd5!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: Arrays and structures Message-ID: <10260@mimsy.UUCP> Date: 20 Jan 88 03:47:51 GMT References: <22151@linus.UUCP> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 58 In article <22151@linus.UUCP> jfjr@mitre-bedford.ARPA (Jerome Freedman) writes: >[Given the (edited) declaration >struct { char string[80]; int vector [4]; } first_structure,second_structure; >and, after setting up first_structure, writing] >second_structure = first_structure; /* ANSI standard allows this */ Yes (as do all modern C compilers). >Now, tell me about the string and vector fields of second structure. >Since they are arrays then the fields are actually pointers. First misconception. They are arrays; nothing else. (Conversion to pointers occurs elsewhere.) >The question is [hard to grasp] The contents of each array is copied, as if you had written int i; for (i = 0; i < 80; i++) second_structure.string[i] = first_structure.string[i]; for (i = 0; i < 4; i++) second_structure.vector[i] = first_structure.vector[i]; Note that uninitialised data may cause a trap: f1() { struct goo { char a, b, c } g1, g2; g2.a = g1.a; /* illegal (g1.a not set) */ g2 = g1; /* illegal (g1 not set) */ } f2() { struct yuk { char str[40] } y1, y2; strcpy(y1.str, "hi"); y2 = y1; /* illegal! (y1.str[3..39] not set) */ /* can someone check and make *sure*? */ } (this is something I had not considered in the `structure copy vs. structure comparison' debate). >Is the situation different if I change the type declaration to (edited) >struct { char *string; int *vector; } first_structure, second_structure; Yes, the situation is quite different, but the operation of the structure assignment is likewise described easily: Each element of the structure is copied entire. Holes may or may not be copied. Elements which are unions are copied `bitwise' in such a way as not to cause a trap. -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163) Domain: chris@mimsy.umd.edu Path: uunet!mimsy!chris