Question

10.3 Name_year in C - phase 3 This lab is part 2 of a series of...

10.3 Name_year in C - phase 3

This lab is part 2 of a series of 3 labs that will walk you through the process of creating a C struct and related functions that are the equivalent of the Name_year class you created in chapter 9.

For this phase, we will

  • Create an init_name_year() function that initializes a Name_year object.
  • Move the object initialization logic from create_name_year() to init_name_year().
  • Create a function called compare_name_year() to compare two Name_year objects.

The function declarations are:

int init_name_year(Name_year * ny, const char * name, int year);
int compare_name_year(const Name_year * ny1, const Name_year * ny2);

init_name_year() should contain all the code originally in create_name_year() that actually initializes the data. That is, it should

  • use malloc() to allocate memory for a copy of the name
  • use strcpy() to copy the name
  • store the year in the struct\

Name_year should return 1 if everything worked (that is, if we were able to allocate memory for the name), and 0 to indicate failure.

compare_name_year() will return a value consistent with the convention elsewhere in the C library (specifically strcmp()). The return value is

  • -1 if ny1 < ny2
  • 0 if ny1 == ny2
  • 1 if ny1 > ny2

One Name_year is considered to be greater than another if the name in one is "greater than" the name in the other, as determined by the strcmp() function. If the names are the same, then the comparison is based on the year. Here is the pseudocode for compare_name_year():

compare the names using `strcmp()`, and store the return value
if strcmp() returned a non-zero value
    return that value
else
    compare the years and return
        

-1 if ny1->year < ny2->year

1 if ny1->year > ny2->year

0 if they are equal

I will review your final code to ensure that the following things are done correctly. You will lose points on the assignment for each one that is not correct:

  • Your code should be reasonably and consistently indented.
  • Your header file must be able to be included twice.
  • All functions must be defined in the source file (Name_year.c).
  • The verify_year() function should be defined in the .c file but not declared in the .h file.
  • create_name_year() should call init_name_year() to initialize the name and year fields in the struct

-----------------------

name_year_test.c is given:


#include "Name_year.h"

#define _CRT_SECURE_NO_WARNINGS

#include
#include
#include

void print_name_year(const Name_year * ny)
{
   printf("%s,%d\n", ny->name, ny->year);
}

int qsort_compare(const void * lhs, const void * rhs)
{
   Name_year * lny = (Name_year *)lhs;
   Name_year * rny = (Name_year *)rhs;
   return compare_name_year(lny, rny);
}

int main()
{
   char * ny_format = "%s,%d\n";

#if PHASE >= 1

   puts("Phase 1 tests");

   // Make sure we can create an object and get the data back.
   // We're creating the name as a local array so that we can
   // make sure that create_name_year() does not merely make
   // a copy of the pointer.
   char stroustrup[20];
   strcpy(stroustrup, "Stroustrup");
   Name_year * ny_stroustrup = create_name_year(stroustrup, 1950);
   stroustrup[0] = '\0';
   print_name_year(ny_stroustrup);

   // Make sure we can create a second object independent from the first one.
   char knuth[20];
   strcpy(knuth, "Knuth");
   Name_year * ny_knuth = create_name_year(knuth, 1938);
   knuth[0] = '\0';
   print_name_year(ny_stroustrup);
   print_name_year(ny_knuth);

   destroy_name_year(ny_stroustrup);
   destroy_name_year(ny_knuth);

#endif

#if PHASE >= 2

   puts("Phase 2 tests");

   // Make sure we can change the year.
   Name_year * ny_dijkstra = create_name_year("Dijkstra", 1980);
   print_name_year(ny_dijkstra);
   set_year(ny_dijkstra, 1930);
   print_name_year(ny_dijkstra);
   destroy_name_year(ny_dijkstra);

   {
       // Make sure the proper status is returned by create_name_year().
       Name_year * ny_lovelace = create_name_year("Lovelace", 1815);
       if (ny_lovelace != NULL)
           puts("Error: invalid status returned for invalid year in create_name_year");
       else
           puts("correct status returned for invalid year in create_name_year");
   }

   // Make sure the proper exception is thrown from set_year().
   Name_year * ny_lovelace = create_name_year("Lovelace", 1915);
   if (set_year(ny_lovelace, 1815))
       puts("Error: invalid status returned for invalid year in set_year");
   else
       puts("Correct status returned for invalid year in set_year");

   // Make sure trying to set an invalid year did not change the object.
   print_name_year(ny_lovelace);
   destroy_name_year(ny_lovelace);

#endif

#if PHASE>=3

   puts("Phase 3 tests");

   // Create a vector of Name_pairs.
   Name_year nys[6];
   init_name_year(&nys[0], "Stroustrup", 1950);
   init_name_year(&nys[1], "Knuth", 1938);
   init_name_year(&nys[2], "Smith", 1961);
   init_name_year(&nys[3], "Smith", 1960);
   init_name_year(&nys[4], "Dijkstra", 1930);
   init_name_year(&nys[5], "Knuth", 1938);

   int num_nys = sizeof(nys) / sizeof(nys[0]);

   // Make sure we can print them out
   puts("");
   puts("Before sorting");
   for (int i = 0; i < num_nys; i++)
       print_name_year(&nys[i]);

   // Make sure the two Knuths are equal.
   int cmp = compare_name_year(&nys[1], &nys[5]);
   if (cmp != 0)
       printf("Error comparing equal items: returned %d for equal objects\n", cmp);

   cmp = compare_name_year(&nys[4], &nys[0]);
   if (cmp != -1)
       printf("Error comparing unequal items: returned %d for object 1 < object2\n", cmp);

   cmp = compare_name_year(&nys[2], &nys[1]);
   if (cmp != 1)
       printf("Error comparing unequal items: returned %d for object 1 > object2\n", cmp);

   cmp = compare_name_year(&nys[3], &nys[2]);
   if (cmp != -1)
       printf("Error comparing unequal items (equal names): returned %d for object 1 < object2\n", cmp);

   // Make sure we can sort. We'll use stable_sort to make sure
   // the year is taken into account (the Smiths should swap relative
   // position).
   qsort(nys, num_nys, sizeof(Name_year), qsort_compare);
   puts("");
   puts("After sorting");
   for (int i = 0; i < num_nys; i++)
       print_name_year(&nys[i]);

#endif

   return 0;
}

-----------------

find name_year.h and name_year.c as stated in the question

0 0
Add a comment Improve this question Transcribed image text
Answer #1
#ifndef NAME_YEAR_H
#define NAME_YEAR_H
typedef struct {
        char * name;
        int year;
}Name_year;

Name_year * create_name_year(const char * name, int year);
void destroy_name_year(Name_year * ny);
int set_year(Name_year* ny, int y);
int init_name_year(Name_year * ny, const char * name, int year);
int compare_name_year(const Name_year * ny1, const Name_year * ny2);


#endif // NAME_YEAR_H

----------------------------------------------Name_year.c-----------------------------

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Name_year.h"

int verify_year(int y) {
        return (y >= 1900);
}

Name_year* create_name_year(const char *name, int year) {
        if(!verify_year(year)) {
                return NULL;
        }

        Name_year *ny = (Name_year*) malloc(sizeof(Name_year));
        if(ny == NULL) {
                return NULL;
        }

        if(init_name_year(ny, name, year)) {
                return ny;
        }
        
        return NULL;
}

void destroy_name_year(Name_year * ny)
{
        free(ny); // delete allocated memory of ny
        ny = NULL; // assign NULL to ny
}

int set_year(Name_year* ny, int y) {
        if(verify_year(y)) {
                ny->year = y;
                return 1;
        }
        return 0;
}

int init_name_year(Name_year * ny, const char * name, int year) {               
        ny->name = (char*) malloc(sizeof(char) * (strlen(name) + 1));
        if(ny->name == NULL) {
                return 0;
        }
        strcpy(ny->name, name);
        ny->year = year;
        return 1;
}


int compare_name_year(const Name_year * ny1, const Name_year * ny2) {
        if(ny1->year < ny2->year) {
                return -1;
        } else if(ny1->year > ny2->year) {
                return 1;
        } else {
                return 0;
        }

}


please upvote. Thanks!

Add a comment
Know the answer?
Add Answer to:
10.3 Name_year in C - phase 3 This lab is part 2 of a series of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Name_year_test.c #include "Name_year.h" #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> void print_name_year(const Name_year * ny) {   ...

    Name_year_test.c #include "Name_year.h" #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> void print_name_year(const Name_year * ny) {    printf("%s,%d\n", ny->name, ny->year); } int main() {    char * ny_format = "%s,%d\n"; #if PHASE >= 1    puts("Phase 1 tests");    // Make sure we can create an object and get the data back.    // We're creating the name as a local array so that we can    // make sure that create_name_year() does not merely make    // a copy of...

  • In this lab, you will write a program that reads a series name/value pairs, and stores...

    In this lab, you will write a program that reads a series name/value pairs, and stores them in a pair of vectors. After the name/value pairs are read, it will then read names (until the input is exhausted) and print out the corresponding value for that name. If the name is not found in the list, "name not found" should be printed. The names should be read as strings and stored as a vector<string>; the values should be read as...

  • Help please this is C/C++ code /* * Lab12, the purpose of this lab is to...

    Help please this is C/C++ code /* * Lab12, the purpose of this lab is to improve your skills in handling c strings * with pointers . * use of : strlen ,string concatenation strcat, compare strcmp, * copy strcpy and search strrchr * */ #include <cstdlib> #include <iostream> #include<cstring> using namespace std; /** * Create a method that prompts the user for only lowercase letters to represent * a name. * Start a Label, then prompt the user to...

  • I need help with this C code Can you explain line by line? Also can you...

    I need help with this C code Can you explain line by line? Also can you explain to me the flow of the code, like the flow of how the compiler reads it. I need to present this and I want to make sure I understand every single line of it. Thank you! /* * Converts measurements given in one unit to any other unit of the same * category that is listed in the database file, units.txt. * Handles...

  • This lab is to give you more experience with C++ Searching and Sorting Arrays Given a...

    This lab is to give you more experience with C++ Searching and Sorting Arrays Given a file with data for names and marks you will read them into two arrays You will then display the data, do a linear search and report if found, sort the data, do a binary search. Be sure to test for found and not found in your main program. Read Data Write a function that reads in data from a file using the prototype below....

  • The following C code keeps returning a segmentation fault! Please debug so that it compiles. Also...

    The following C code keeps returning a segmentation fault! Please debug so that it compiles. Also please explain why the seg fault is happening. Thank you #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> // @Name loadMusicFile // @Brief Load the music database // 'size' is the size of the database. char** loadMusicFile(const char* fileName, int size){ FILE *myFile = fopen(fileName,"r"); // Allocate memory for each character-string pointer char** database = malloc(sizeof(char*)*size); unsigned int song=0; for(song =0; song < size;...

  • please rewrite or convert this C program into Assembly language and please make a notice of...

    please rewrite or convert this C program into Assembly language and please make a notice of which function is which! #include <stdio.h> #include <stdlib.h> void printMonthYear(int mon,int year); void printDaysOfWeek(); void printDays(int mon,int year); int getFirstDayOfMonth(int mon, int year); int getNumOfDaysInMonth(int mon, int year); int main(void) {    int mon=-1; int year= -1; printf("Month : "); fflush(stdout); scanf("%d",&mon);    if(mon < 1|| mon > 12){ printf("Invalid month >.<!: %d ! Must be between 1 and 12\n",mon); return 1; } printf("Year...

  • Help with programming in C++ Phase 1 is complete, please help with phase 2. Thank you....

    Help with programming in C++ Phase 1 is complete, please help with phase 2. Thank you. Phase 1 You must design 3 algorithms, and provide both a flow chart and pseudo code for the algorithms.    Algorithm descriptions: Given an integer parameter named current_number and two constant global variables: const int MIN_NUMBER = 1; const int MAX_NUMBER = 8; Create an algorithm named forward, that will advance ONE value through a sequence of numbers 1, 2, 3 ... MAX_NUMBER. In...

  • please write the code in C++ 2 Base class File 3 Derived class PDF 3.1 Class...

    please write the code in C++ 2 Base class File 3 Derived class PDF 3.1 Class declaration • The class PDF inherits from File and is a non-abstract class 1. Hence objects of the class PDF can be instantiated. 2. To do so, we must override the pure virtual function clone) in the base class • The class declaration is given below. • The complete class declaration is given below, copy and paste it into your file. . It is...

  • How do I set up my read function? here's my code so far: int read_sudoku_board(const char file_name[], int board[9][9]) { FILE * fp = fopen("sudoku.txt", "r"); int a,i,j,c;...

    How do I set up my read function? here's my code so far: int read_sudoku_board(const char file_name[], int board[9][9]) { FILE * fp = fopen("sudoku.txt", "r"); int a,i,j,c; int count = 0; for(i = 0; i < a; i++){ for(j = 0;j < 9;j++){ c = fgetc(fp); if(c == '-'){ board[i][j] = 0; } else if(c >= 1 && c <= 9) printf(" %d"); else return -2; } count++; } if(count != a-1) return -1; else return 0; }12 Read...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT