Yesterday I learned about data structure and I tried making my very first code related to it. What I learned about structure is it is just like any other data type (eg. int, char). What differentiate structucture from an ordinary data type is that it can hold a different type of data. So a structure is a container of any number of variable of any data type and even a structure itself (nested structure) . I also tried typedef. See below for the practice code I did yesterday:
#include <iostream>
#include <string>
using namespage std;
struct person_test {
int age;
string name;
} girl, boy;
//struct using typedef. with typedef it will create an alias
typedef struct second_practice {
int age;
string name;
int year_birth;
} THISISIT;
int main ()
{
girl.age = 28;
boy.age = 27;
girl.name = “Tzekoi”;
boy.name = “Makoi”
cout << “GIRL” << endl;
cout << “Name: ” << girl.name << endl;
cout << “Age: ” << girl. age << endl << endl;
cout << “Boy” << endl;
cout << “Name: ” << girl.name << endl;
cout << “Age: ” << girl. age << endl << endl; //Secod practice
THISISIT *chingot; //Instead of “struct second_practice” it gets replaced with THISISIT
THISISIT makoi;
chingot = &makoi; //chingot->age is the same with (*chingot).age
chingot->age = 28;
chingot->year_birth = 1984;
chingot->name = “Tzekoi”;
cout << “Second Examople” << endl;
cout << “Age: ” << chingot->age << endl;
cout << “Name: ” << chingot->name << endl;
cout << “Year: ” << chingot->year_birth << endl << endl;
cout << “Age: ” << makoi.age << endl;
cout << “Name: ” << makoi.name << endl;
cout << “Year: ” << makoi.year_birth << endl << endl;
makoi.name = “Makoi”;
makoi.year_birth = 1984;
makoi.age = 27;
cout << “Age: ” << chingot->age << endl;
cout << “Name: ” << chingot->name << endl;
cout << “Year: ” << chingot->year_birth << endl << endl;
cout << “Age: ” << (*chingot).age << endl;
cout << “Name: ” << (*chingot).name << endl;
cout << “Year: ” << (*chingot).year_birth << endl << endl;
}
Today I also learned about Dynamic Memory Allocation. From the word Dynamic Memory Allocation we can easily get an idea that is about assigning memory on run time. How to do this I have based the sample code I tried on the very comprehensive site for c++ tutorial http://www.cplusplus.com/doc/tutorial/dynamic/. The following lines of code I have run:
#include<iostream>
#include<new>
using namespace std;
int main ()
{
int *pChing;
int index = 5;
pChing = new (nothrow) int[index];
if (pChing == 0)
{
cout << “ERROR: memory could not be allocated”;
} else {
for (int i = 0; i < index; i++ )
{
pChing[i] = i;
}
for (int i = 0; i < index; i++)
cout << pChing[i] << endl;
delete[] pChing;
}
return 0;
}