🎯

STRUCT

TypeQuiz 4 Material

Structures

Collection of items which may be of different types

Same as classes in Java

Structs

If given a pointer to a struct, use the -> operator to simultaneously dereference and access it

Structs declaration

struct [ <optional tag> ] [ {
	<type declaration>;
	<type declaration>;
	...
} ] [ <optional variable list> ];

Struct Initialization

struct mystruct_tag {
	int myint;
	char mychar;
	char mystr[20];
};
struct mystruct_tag ms = {42, 'f', "goofy"};

Two same way of struct implementation

struct Dog {
   char name[20];
   int isGood;
};

int main(void) {
   struct Dog dog = dogs[5];
   strncpy(dog.name, "Doggo", 6);
   dog.isGood = 1; // true
}
is equivalent to
int main(void) {
   struct Dog *dog = &dogs[5];
   strncpy(dog->name, "Doggo", 6);
   dog->isGood = 1; // true
}

Struct in memory

struct Dog {
   char name[20];
   int isGood;
   int age;
};
struct Dog my_dog;
//Assume sizeof(int) == 4 and struct starts at x4000
AddressAt the AddressData Type
x4000name[0]char
x4001name[1]char
x4002name[2]char
x4003..x4013name[3] - name[19]char
x4014isGoodint
x4018ageint

Copying Structs

struct s {
	int i;
	char c;
} s1, s2;
s1.i = 42;
s1.c = 'a';
s2 = s1; //for loop copy of s1 to s2. Cloning
s1.c = 'b';
s2.i //42
s2.c //a
//Note that assigning the structure just copied the 
//bytes from one memory block to another. There is 
//no connection between them.
struct s {
	int i;
	char c[8];
} s1, s2;
s1.i = 42;
strcpy(s1.c, "foobar"); 
s2 = s1; 
//Since we assigned s1 to s2, s2.c is going to contain 
//exactly the same characters as are in s1.c, even 
//including the unspecified character at s1.c[7]!
s2.i //42
s2.c //'f','o','o','b','a','r','\0'

Memory Storage

struct {
	char mychar; 
	int myint;
	char mystr[19];
} mystruct;
#include <stdio.h>
struct {
	char mychar; 
	int myint;
	char mystr[19];
} mystruct;
int main() {
	printf("Address of mystruct = %p\n", (void *)&mystruct);
	printf("Offset of mychar = %ld\n",
	(void *)&mystruct.mychar - (void *)&mystruct);
	printf("Offset of myint = %ld\n",
	(void *)&mystruct.myint - (void *)&mystruct);
	printf("Offset of mystr = %ld\n",
	(void *)mystruct.mystr - (void *)&mystruct);
	printf("Size of mystruct = %ld\n", sizeof(mystruct));
}
/*
$ gcc sizes.c
$ ./a.out
Address of mystruct = 0x10ae74018
Offset of mychar = 0
Offset of myint = 4
Offset of mystr = 8
Size of mystruct = 28
*/

Indexing into a String

Arrays of Structs

Summary

Struct may

Struct may not