Exercise 3-15 (Student, typedef, struct pointers in C/C++)

Chapter_3     Exercise_3-14     SimpleStruct3 Enum     Exercise_3-16







Exercise 3-15     TCP1, p. 228


Exercise 3-15. Create a struct that holds two string objects and one int. Use a typedef for the struct name. Create an instance of the struct, initialize all three values in your instance, and print them out. Take the address of your instance and assign it to a pointer to your struct type. Change the three values in your instance and print them out, all using the pointer.




CONTENTS:     student.c     Student.cpp




student.c         download


#include <stdio.h> // for printf()
#include <string.h> // for strcpy()

#define SIZE 100

typedef struct Student // type name `struct Student' defined in C
{
int age;
char firstName[SIZE];
char lastName[SIZE];
} Student; // type name `Student' defined here

void print(struct Student s);
void print(struct Student);
void print(Student s);
void print(Student);

int main()
{
struct Student s; // Student s;

s.age = 18;
strcpy(s.firstName, "John");
strcpy(s.lastName, "Doe");

print(s);

struct Student* sp = &s; // Student* sp = &s;

(*sp).age = 19; // sp->age
strcpy(sp->firstName, "Jane"); // (*sp).firstName
strcpy(sp->lastName, "Dove");

print(*sp); // s

return 0;
}

void print(Student s)
{
printf("%s %s (%d)\n", s.firstName, s.lastName, s.age);
}
/*
gcc student.c -o student
./student
John Doe (18)
Jane Dove (19)
*/











Student.cpp         download


#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;

typedef struct Student // type names `Student',
{ // `struct Student' defined in C++
int age;
string firstName;
string lastName;
} Student; // superfluous in C++
// (works without typedef...Student):
/*
struct Student // type names `Student',
{ // `struct Student' defined in C++
int age;
string firstName;
string lastName;
};
*/

void print(struct Student s);
void print(struct Student);
void print(Student s);
void print(Student);

int main()
{
struct Student s; // Student s;

s.age = 18;
s.firstName = "John";
s.lastName = "Doe";

print(s);

struct Student* sp = &s; // Student* sp = &s;

(*sp).age = 19; // sp->age
sp->firstName = "Jane"; // (*sp).firstName
sp->lastName = "Dove";

print(*sp); // s

return 0;
}

void print(Student s)
{
cout << s.firstName << " " << s.lastName
<< " (" << s.age << ")" << endl;
}
/*
g++ Student.cpp -o Student
./Student
John Doe (18)
Jane Dove (19)
*/









Chapter_3     Exercise_3-14     SimpleStruct3 BACK_TO_TOP Enum     Exercise_3-16



Comments

Popular posts from this blog

Contents