Discussion Notes 8

Discussion Notes 8 - EME 5 Fall 2007 Discussion 8 Declare a...

Info iconThis preview shows pages 1–6. Sign up to view the full content.

View Full Document Right Arrow Icon
EME 5 Fall 2007 Discussion 8 Declare a structure or a pointer to structure Two common ways to declare a structure or a pointer to structure: struct Student { int id; char name[32]; }; int main() { struct Student s1, *s2; . . . return 0; } or struct Student { int id; char name[32]; } s1, *s2; int main() { . . . return 0; }
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Access elements of a structure /* ex1.c */ #include <stdio.h> struct Student { int id; char name[32]; }; int main() { struct Student s1, *s2; s1.id = 101; strcpy(s1.name, "Yu-Cheng Chou"); s2 = &s1; printf("s1.id = %d\n\n", s1.id); printf("s1.name = %s\n\n", s1.name); printf("*(s1.name) = %c\n", *(s1.name)); printf("s1.name[0] = %c\n\n", s1.name[0]); printf("*((s1.name)+7) = %c\n", *((s1.name)+7)); printf("s1.name[7] = %c\n\n", s1.name[7]); printf("s2->id = %d\n\n", s2->id); printf("s2->name = %s\n\n", s2->name); printf("*(s2->name) = %c\n", *(s2->name)); printf("s2->name[0] = %c\n\n", s2->name[0]); printf("*((s2->name)+7) = %c\n", *((s2->name)+7)); printf("s2->name[7] = %c\n\n", s2->name[7]); return 0; }
Background image of page 2
Memory address Computer memory Variable name id s1 1000 name 1004 1011 101 ‘Y’ ‘u’ ‘-’ ‘C’ ‘h’ ‘e’ ‘n’ ‘g’ ‘ ’ ‘C’ ‘h’ ‘o’ ‘u’ ‘\0’ s2 2000 1000 2003
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Initialize a structure Two common ways to initialize a structure: struct Student { int id; char name[32]; }; int main() { struct Student s1 = {100, “Yu-Cheng Chou”}; . . . return 0; } or struct Student { int id; char name[32]; } s1 = {100, “Yu-Cheng Chou”}; int main() { . . . return 0; }
Background image of page 4
Assign a structure to another structure After we declare a structure and initialize the structure or assign values to all the structure’s elements, we can assign this structure to another structure by statements such as
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 6
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 04/21/2008 for the course EME 005 taught by Professor Cheng during the Fall '07 term at UC Davis.

Page1 / 14

Discussion Notes 8 - EME 5 Fall 2007 Discussion 8 Declare a...

This preview shows document pages 1 - 6. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online