C/Structure/Struct Define

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Define and use a struct

<source lang="cpp">

  1. include <stdio.h>

struct struct_type {

 int i;
 char ch;
 double d;
 char str[80];

} s; int main(void) {

 printf("Enter an integer: ");
 scanf("%d:", &s.i);
 
 printf("Enter a character: ");
 scanf(" %c", &s.ch);
 
 printf("Enter a floating point number: ");
 scanf("%lf", &s.d);
 
 printf("Enter a string: ");
 scanf("%s", s.str);
 printf("%d %c %f %s", s.i, s.ch, s.d, s.str);
 return 0;

}


      </source>


Define a simplest struct

<source lang="cpp">

  1. include <stdio.h>

int main(void) {

 struct {
   int a;
   int b;
 } x, y; 
 x.a = 10;
 y = x;  /* assign one structure to another */
 printf("%d", y.a);
 return 0;

}


      </source>


Exercising the horse: Structure declaration

<source lang="cpp">

  1. include <stdio.h>

struct cat {

 int age;
 int height;
 char name[20];
 char father[20];
 char mother[20];

}; void main() {

  struct cat myCat;
  printf("Enter the name of the cat: " );
  scanf("%s", myCat.name );
  printf("How old is %s? ", myCat.name );
  scanf("%d", &myCat.age );
  printf("How high is %s ( in hands )? ", myCat.name );
  scanf("%d", &myCat.height );
  printf("Who is %s"s father? ", myCat.name );
  scanf("%s", myCat.father );
  printf("Who is %s"s mother? ", myCat.name );
  scanf("%s", myCat.mother );
  printf("\n%s is %d years old, %d hands high,", myCat.name, myCat.age, myCat.height);
  printf(" and has %s and %s as parents.\n", myCat.father,myCat.mother );

}

      </source>


How to use struct

<source lang="cpp">

struct student {

 char name[30];  
 float number;

} student1, student2;

main () {

 struct student student3;
 char s1[30];
 float  f;
 scanf ("%s", s1);
 scanf ("%f", &f);
 student1.name = s1;
 student2.number = f;
   printf ("Name = %s \n", student1.name);
   printf ("Number = %f \n", student2.number);

}

      </source>


Pointing out the horses: allocate memory for struct

<source lang="cpp">

  1. include <stdio.h>
  2. include <ctype.h>
  3. include <stdlib.h> /* For malloc() */

struct cat {

    int age;
    int height;
    char name[20];
    char father[20];
    char mother[20];

}; void main() {

  struct cat *pcat[50];
  int hcount = 0;
  int i = 0;
  char test = "\0";
  for(hcount = 0; hcount < 50 ; hcount++ )
  {
    printf("Do you want to enter details of a%s cat (Y or N)? ",hcount?"nother " : "" );
    scanf(" %c", &test );
    if(tolower(test) == "n")
      break;
    pcat[hcount] = (struct cat*) malloc(sizeof(struct cat));
    printf("\nEnter the name of the cat: " );
    scanf("%s", pcat[hcount]->name );
    printf("\nHow old is %s? ", pcat[hcount]->name );
    scanf("%d", &pcat[hcount]->age );
    printf("\nHow high is %s ( in hands )? ", pcat[hcount]->name );
    scanf("%d", &pcat[hcount]->height );
    printf("\nWho is %s"s father? ", pcat[hcount]->name );
    scanf("%s", pcat[hcount]->father );
    printf("\nWho is %s"s mother? ", pcat[hcount]->name );
    scanf("%s", pcat[hcount]->mother );
  }
  for (i = 0 ; i < hcount ; i++ )
  {
    printf("\n\n%s is %d years old, %d hands high,", pcat[i]->name, pcat[i]->age, pcat[i]->height);
    printf(" and has %s and %s as parents.", pcat[i]->father, pcat[i]->mother);
    free(pcat[i]);
  }

}


      </source>


Using a structure representing a length

<source lang="cpp">

  1. include <stdio.h>
  2. include <ctype.h>
  3. define INCHES_PER_FOOT 12
  4. define FEET_PER_YARD 3

struct Length {

 unsigned int yards;
 unsigned int feet;
 unsigned int inches;

}; struct Length add(struct Length first, struct Length second); void show(struct Length length); int main() {

 char answer = "n";
 struct Length length;
 struct Length total = { 0,0,0};
 int i = 0;
 length.yards =9;
 length.feet = 10;
 length.inches = 1;
 total = add(total,length);
 show(total);
 printf("\n");

} struct Length add(struct Length first, struct Length second) {

 unsigned long inches = 0;
 struct Length sum;
 inches = first.inches + second.inches+
   INCHES_PER_FOOT*(first.feet+second.feet+FEET_PER_YARD*(first.yards+second.yards));
 sum.inches = inches%INCHES_PER_FOOT;
 sum.feet = inches/INCHES_PER_FOOT;
 sum.yards = sum.feet/FEET_PER_YARD;
 sum.feet %= FEET_PER_YARD;
 return sum;

} void show(struct Length length) {

 printf("%d yards %d feet %d inches", length.yards,length.feet, length.inches);

}


      </source>


Using a structure representing a person"s name

<source lang="cpp"> /* Beginning C, Third Edition

By Ivor Horton
ISBN: 1-59059-253-0
Published: Apr 2004
Publisher: apress
  • /
  1. include <stdio.h>
  2. include <string.h>
  3. include <ctype.h>
  4. define FIRST_NAME_LEN 31
  5. define SECOND_NAME_LEN 51
  6. define NUMBER_LEN 16
  7. define MAX_NUMBERS 50
  8. define TRUE 1
  9. define FALSE 0

/* Structure defining a name */ struct Name {

 char firstname[FIRST_NAME_LEN];
 char secondname[SECOND_NAME_LEN];

}; /* Structure defining a phone record */ struct PhoneRecord {

 struct Name name;
 char number[NUMBER_LEN];

}; struct Name read_name(); /* Read a name from the keyboard */ void show(struct PhoneRecord record); /* Output a phone record */ int has_name(struct PhoneRecord record, struct Name name); /* Test for a name */ void main() {

 char answer = "n";
 struct PhoneRecord records[MAX_NUMBERS];  /* Array of phone records  */
 struct Name aName;                        /* Stores a name           */
 int count = 0;                            /* Number of phone records */
 int found = FALSE;                        /* Records when a name has been found */
 int i = 0;                                /* Loop control variable   */

 /* Read an arbitrary number of phone records from the keyboard */  
 do
 {
   records[count].name = read_name();                 /* Read the name */      
   printf("Enter the number for this name: ");
   scanf(" %[ 0123456789]",records[count++].number);  /* Read the number - including spaces */
   printf("Do you want to enter another(y or n)?: ");
   scanf(" %c", &answer);
 }while(count<=MAX_NUMBERS && tolower(answer) == "y");
 /* Search the array of phone records for a number */
 do
 {
   printf("Enter a name for which you want the number.");
   aName =read_name();
   for(i = 0 ; i<count ; i++)
   {
     if(has_name(records[i], aName))                 /* Test for the name */
     {
       if(!found)                                    /* If this is the first time */
       {
         found = TRUE;                               /* Reset found flag       */
         printf("The numbers for this name are:\n"); /* and output the heading */
       }
       printf("%s\n", records[i].number);            /* Output the number for the name */
     }
   }
   if(found)                                         /* If the name was found */
     found = FALSE;                                  /* Reset the found flag  */
   else                                              /* Otherwise output message */
     printf("No numbers found for this name.\n");
   printf("Do you want to search for another (y or n)? ");
   scanf(" %c" , &answer);
 }while(tolower(answer) == "y");
 for(i = 0 ; i<count ; i++)
   show(records[i]);
 printf("\n");

} /* Function to read a name and store it in a Name structure */ struct Name read_name() {

 struct Name name;
   printf("Enter a first name: ");
   scanf(" %s", &name.firstname);
   printf("Enter a second name: ");
   scanf(" %s", &name.secondname);
 return name;

} /* Function to output a record */ void show(struct PhoneRecord record) {

 printf("\n%s %s   %s", record.name.firstname,record.name.secondname, record.number);

} /* Function to test whether the name is the same as in a record */ int has_name(struct PhoneRecord record, struct Name name) {

 return (strcmp(name.firstname, record.name.firstname)==0 && strcmp(name.secondname, record.name.secondname)==0);

}


      </source>


Using a structure to record the count of occurrences of a word

<source lang="cpp"> /* Beginning C, Third Edition

By Ivor Horton
ISBN: 1-59059-253-0
Published: Apr 2004
Publisher: apress
  • /

/*

 This program defines a structure that stores a word and the count of its occurrences.
 The structures are stored as they are created in a linked list. If you wanted the
 output in alphabetical order, you could insert the structures in the list to ensure
 that the list was ordered. Alternatively you could sort the list.
  • /
  1. include <stdio.h>
  2. include <string.h>
  3. define MAX_WORD_LENGTH 31
  4. define MAX_TEXT_LENGTH 10000
  5. define TRUE 1
  6. define FALSE 0

/* Structure defining a count of the occurrences of a given word */ struct WordCounter {

 char *word;
 int word_count;
 struct WordCounter *pNext;                        /* Pointer to the next word counter in the list */

}; /* Function prototypes */ void addWord(char *pWord); /* Adds a word to the list or updates exisiting word */ int is_separator(char ch); /* Tests for a separator character */ void show(struct WordCounter *pWordcounter); /* Outputs a word and its count of occurrences */ struct WordCounter* createWordCounter(char *word); /* Creates a new WordCounter structure */ /* Global variables */ struct WordCounter *pStart = NULL; /* Pointer to first word counter in the list */

void main() {

 char text[MAX_TEXT_LENGTH];           /* Stores input text         */
 char buffer[MAX_WORD_LENGTH];         /* Buffer to hold a word     */
 size_t i = 0;                         /* Index to text             */
 int len = 0 ;                         /* Word length               */
 struct WordCounter *pCounter = NULL;  /* Pointer to a word counter */      
 /* Read the text from the keyboard */
 printf("Enter the text:\n");
 gets(text);
 /* Extract the words from the text  */  
 while(text[i] != "\0")
 {
   /* Skip over separators */
   while(is_separator(text[i]))
     ++i;
   /* It is either the end of the string or the start of a word    */
   /* As long as it is not the string terminator copy the character */
   len = 0;              /* Reset character count    */
   while((!is_separator(text[i])) && (text[i] != "\0"))
     buffer[len++] = text[i++];
   if(len>0)               /* Check we have some characters in the word */
   {
     buffer[len] = "\0";   /* We reached the end of a word so add terminator */
     addWord(buffer);      /* Add the word to the list */
   }
 }
 /* List the words and their counts */
 pCounter = pStart;
 while(pCounter != NULL)
 {
   show(pCounter);
   pCounter = pCounter->pNext;
 }
 printf("\n");
 /* Free the memory that we allocated */
 pCounter = pStart;
 while(pCounter != NULL)
 {
   free(pCounter->word);        /* Free space for the word */
   pStart = pCounter;           /* Save address of current */
   pCounter = pCounter->pNext;  /* Move to next counter    */
   free(pStart);                /* Free space for current  */     
 }

} /* Returns TRUE if the argument is a separator character and FALSE otherwise */ int is_separator(char ch) {

 /* Separators are space, comma, colon, semicolon, double quote, question mark, exclamation, and period */
 static char separators[] = { " " , ",",":" , "\"", "?" , "!" , "."};
 int i = 0;
 for(i = 0 ; i<sizeof separators ; i++)
 {
   if(ch == separators[i])
     return TRUE;
 }
 return FALSE;

} void show(struct WordCounter *pWordcounter) {

 /* output the word left-justified in a fixed field width followed by the count */
 printf("\n%-30s   %5d", pWordcounter->word,pWordcounter->word_count);

} void addWord(char *word) {

 struct WordCounter *pCounter = NULL;
 struct WordCounter *pLast = NULL;
 if(pStart == NULL)
 {
   pStart = createWordCounter(word);
   return;
 }
 /* If the word is in the list, increment its count */
 pCounter = pStart;
 while(pCounter != NULL)
 {
   if(strcmp(word, pCounter->word) == 0)
   {
     ++pCounter->word_count;
     return;
   }
   pLast = pCounter;            /* Save address of last in case we need it */
   pCounter = pCounter->pNext;  /* Move pointer to next in the list        */
 }

 /* If we get to here it"s not in the list - so add it */
 pLast->pNext = createWordCounter(word);

} /* Create and returns a new WordCounter object for the argument */ struct WordCounter* createWordCounter(char *word) {

 struct WordCounter *pCounter = NULL;
 pCounter = (struct WordCounter*)malloc(sizeof(struct WordCounter));
 pCounter->word = (char*)malloc(strlen(word)+1);
 strcpy(pCounter->word, word);
 pCounter->word_count = 1;
 pCounter->pNext = NULL;
 return pCounter;

}


      </source>