Review of Structures in C

We use structures when we want to process multiple data types while still referring to the data as a single entity. For instance, we can create a structure and name it student; this structure will contain two data items called fields. One field will be called name and be of type char, the other field will be called score and be of type double.

#include 
#include 

struct student
{
 char name[30];
 double score;
} studentOne, studentTwo;

int main(void){

 char s1[30];
 double d;

 printf("Name: ");
 scanf(" %s:", s1);
 printf("Score: ");
 scanf(" %lf", &d);

 strcpy(studentOne.name, s1);
 studentOne.score = d;

 printf("%s \t %f\n", studentOne.name, studentOne.score);


 return 0;

}

Note that when using scanf() to get a double value, we should use the conversion specifier %lf, as we are passing the function a pointer and not a variable.

We can have structures that have nested structures within them.

#include 
#include 

struct address{
	char street[30];
	char city[30];
	char state[2];
	int zip;
};

struct worker{
	unsigned int id;
	char name[30];
	struct address addr;
};

int main(void){

	struct worker mike;

	mike.id = 1138;
	strcpy(mike.name, "Mike");
	strcpy(mike.addr.street, "1428 Elm Street");
	strcpy(mike.addr.city, "Madison"),
	strcpy(mike.addr.state, "WI");
	mike.addr.zip = 53705;

	printf("#%d %s\n", mike.id, mike.name);
	printf("%s \n%s, %s %d\n", mike.addr.street, mike.addr.city, mike.addr.state, mike.addr.zip);

	return 0;
		
}

Don’t forget to put the semicolon at the end of the structure definition.

Note that structure members are allocated consecutive memory locations.

 #include <stdio.h>
#include <string.h>
//compiling on a Windows machine today
//so I include windows.h for malloc()
#include <Windows.h>

struct album{
char name[30];
char band[30];
int year;
};

struct album* GetAlbum(){
struct album *returnAlbum = (struct album*)malloc(sizeof(struct album));

strcpy(returnAlbum->name, “The North Borders”);
strcpy(returnAlbum->band, “Bonobo”);
returnAlbum->year = 2013;

return returnAlbum;
}

void PrintAlbum(struct album *a){
printf(“Album name = %s\n”, a->name);
printf(“Band name = %s\n”, a->band);
printf(“Year = %d\n”, a->year);
}

int main(void){

struct album *ptrAlbum = GetAlbum();

PrintAlbum(ptrAlbum);

free(ptrAlbum);

return 0;

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s