Thread: Structures on functions

  1. #1
    Registered User
    Join Date
    Nov 2018
    Posts
    12

    Structures on functions

    I need to use structure variables on a function but when compiling, get an error.
    I need to create a function (homework) to compare different data from a structure.
    Code:
    //Structure definition
    
    typedef struct {
        char text1[5], text2[5];
        int val1, val2;
        boolean hasSome;
    }tCar;
    
    //tCar variable declaration
    tCar car1, car2;
    now I need to compare all structure variables using a function to return the following value considering next requirements (strings comparsion is made depending of the initial character in alphabetic order):

    if car1> car2 = 1 //if a parameter of car1 is bigger than car1, return 1
    if car2> car1 = -1 //if a parameter of car2 is bigger than car1, return -1
    if car1 = car2 = 0 //if all compared variables are equal, the function returns 0

    So could you help in order to create a function that compare all the parameters returning a value for each case?
    (I'm really new with C, just some days ago programming).

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Start with this first:
    Code:
    typedef struct {
        int val1;
    } tCar;
    What have you tried for the comparison function?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Nov 2018
    Posts
    12
    I'm not sure about the function header and body...

    I've tried:

    Code:
    //header
    int car_cmp (tCar car1, tCar car2) { //but got an error of undefined tCar
    About the body, I understand I should use strcmp function for strings comparison (for all other variables no problem), but not sure of how to use it...perhaps:

    Code:
    int text_cmp;
    int result;
    text_cmp = strcmp(text1, text2);
    if (text_cmp > 0) {
    result = 1;
    if (text_cmp < 0) {
    result = -1;
    if (text_cmp) ==0){
    result = 0;
    
    //function return
    }return result;
    Is this right?

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > //but got an error of undefined tCar
    Are you sure the typedef is before the function definition in your source code?

    Your understanding of strcmp is correct.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    Nov 2018
    Posts
    12
    I just paste the code I have now (just one comparison):

    Code:
    //System header files
    #include <stdio.h>
    #include <string.h>
    
    
    //constants
    int const MAX_CHAR = 10;
    
    
    //function Header
    int car_cmp(tCar car1, tCar car2);
    
    
    //Main function
    int main(int argc, char* argv[]) {
    	typedef struct{
    	  char carBrand[MAX_CHAR];
    	  char carModel[MAX_CHAR];
    	}tCar;
    	tCar car1, car2;
    	printf("Introduce car1 Brand Text: ");
    	scanf("%s", car1.carBrand);
    	printf("Introduce car2 Brand Text: ");
    	scanf("%s", car2.carBrand);
      	printf("Introduce car1 Model Text: ");
    	scanf("%s", car1.carModel);
    	printf("Introduce car2 Model Text: ");
    	scanf("%s", car2.carModel);
    	
    	printf("the result of comparing the two cars is: %d", car_cmp(result)); //function call
    
    
       return 0;
    }
    
    
    int car_cmp(tCar car1, tCar car2){
    	int text_cmp;
    	int result;
    	text_cmp = strcmp(car1.carBrand, car2.carBrand);
    	if (text_cmp>0){
    		result = 1;
    	}
    }return result;
    And now got these errors / warnings:

    Code:
    /*error: unknown type name 'tCar'; did you mean 'char'?
    Code:
     int car_cmp(tCar car1, tCar car2);
                 ^~~~
                 char
     error: unknown type name 'tCar'; did you mean 'char'?
     int car_cmp(tCar car1, tCar car2);
                            ^~~~
                            char
     warning: implicit declaration of function 'car_cmp'; did you mean 'strncmp'? [-Wimplicit-function-declaration]
      printf("the result of comparing the two cars is: %d", car_cmp(result));
                                                            ^~~~~~~
                                                            strncmp
     error: 'result' undeclared (first use in this function)
      printf("the result of comparing the two cars is: %d", car_cmp(result));
                                                                    ^~~~~~
     error: unknown type name 'tCar'; did you mean 'char'?
     int car_cmp(tCar car1, tCar car2){
                 ^~~~
                 char
    error: unknown type name 'tCar'; did you mean 'char'?
     int car_cmp(tCar car1, tCar car2){
                            ^~~~
                            char
     error: expected identifier or '(' before 'return'
     }return result;
    
    
    ====6 errors, 2 warnings====*/
    

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Like I said, you need to declare the typedef before you reference it.

    Your car_cmp function has changed from what you posted, and the final return is OUTSIDE the closing brace.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  7. #7
    Registered User
    Join Date
    Nov 2018
    Posts
    12
    but there's a car_cmp header before, telling to main that car_cmp function exists. Is not the puropose of a header declaration? if not, could you please show me an example?

  8. #8
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by Akeold View Post
    but there's a car_cmp header before, telling to main that car_cmp function exists. Is not the puropose of a header declaration? if not, could you please show me an example?
    That tells it that the function exists. It does not tell it what a tCar is. You have to tell it what a tCar is before you can use it. In fact your function doesn't know what a tCar is either, because that definition is hidden in main and is only accessible inside main, and therefore not available to the function.

  9. #9
    Registered User Kernelpanic's Avatar
    Join Date
    Sep 2018
    Location
    Berlin
    Posts
    105
    @Akeold - In your code was too many mistakes so I have written a struct-program new; good exercise for me.

    Working with structures and functions is not so simple but I hope this example will help you to understand it a little bit better.

    For "typedef" look in a book for C-programming, it is also without "typedef" but this declaration has some advantages.

    The result is a comparison of purchase price to PS. The screenshot shows two examples:
    1. Bsp
    Pontiac 120,79 zu Firebird: 119,33 ($ or Euro)
    Firebird is more favorable.

    2. Bsp
    Pontiac 120,79 zu Firebird: 165,42 ($ or Euro)
    Pontiac is more favorable.

    Code:
    //Übung mit Strukturen - 8./10. November 2018
    
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    
    //New data type: AUTO
    typedef struct
    {
        char firma[30];
        char modell[30];
        float ps;
        float preis;
    }AUTO;
    
    //Structures as an argument of a function
    int vergleich(AUTO *zgr_wagen1, AUTO *zgr_wagen2);
    
    int main(void)
    {
        //Structur variables
        AUTO wagen1, wagen2;
        
        //Pointers for an access of structures
        AUTO *zgr_w1, *zgr_w2;
        
        //Allacation of the adresses of both structures
        //Zuweisung der Adressen der beiden Strukturen
        zgr_w1 = &wagen1;
        zgr_w2 = &wagen2;
        
        int vergleich_ergebnis;
        
        //Daten einlesen
        printf("\nFirma    : ");
        gets(wagen1.firma);
        printf("Modell   : ");
        gets(wagen1.modell);
        printf("Anzahl PS: ");
        scanf("%f", &wagen1.ps);
        printf("Preis    : ");
        scanf("%f", &wagen1.preis);
        fflush(stdin);   //Eingabepuffer loeschen
        
        printf("\nFirma    : ");
        gets(wagen2.firma);
        printf("Modell   : ");
        gets(wagen2.modell);
        printf("Anzahl PS: ");
        scanf("%f", &wagen2.ps);
        printf("Preis    : ");
        scanf("%f", &wagen2.preis);
        fflush(stdin);
        
        vergleich_ergebnis = vergleich(zgr_w1, zgr_w2);
        printf("\nVergleich von Kaufpreis zu PS\n\n");
        if(vergleich_ergebnis == 0)
            { printf("Das Verhaeltnis von Kaufpreis zur Anzahl PS ist gleich."); }
        else if(vergleich_ergebnis == 1)
            { printf("Der %s hat das bessere Preis- Leistungsverhaeltnis.", wagen1.modell); }
        else
            { printf("Der %s hat das bessere Preis- Leistungsverhaeltnis.\n", wagen2.modell); }
        
        printf("\n\nGIMMICK:\n");
        printf("%5.2f PS sind %5.2f KW\n", zgr_w1->ps, (zgr_w1->ps / 1.36));    
        
        return(0);
    }
    
    int vergleich(AUTO *zgr_wagen1, AUTO *zgr_wagen2)
    {
        float wagen1_ps, wagen2_ps;
        float wagen1_preis, wagen2_preis;
        
        float preis_leistung1;
        float preis_leistung2;
        
        //'->' arrow operator - is equal with '(*zgr_wagen1).ps'
        wagen1_ps = zgr_wagen1->ps;
        wagen1_preis = zgr_wagen1->preis;
        
        wagen2_ps = zgr_wagen2->ps;
        wagen2_preis = zgr_wagen2->preis;
            
        //Price pro PS/KW
        preis_leistung1 = (wagen1_preis / wagen1_ps);
        preis_leistung2 = (wagen2_preis / wagen2_ps);
            
        //Compare purchase price to PS
        //How many Dollar/Euro for one PS/KW
        if(preis_leistung1 == preis_leistung2)
        {
            return(0);
        }
        else if(preis_leistung1 < preis_leistung2)
        {
            return(1);        
        }
        else { return(2); }        
    }
    After editing the representation of the code is changed.

    Structures on functions-autostruktur2018-11-jpg
    Last edited by Kernelpanic; 11-10-2018 at 10:42 AM.

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Kernelpanic: gets is inherently vulnerable to buffer overflow. You must never use it. Consider alternatives like fgets and scanf with %s and a field width instead.

    Also, note that fflush(stdin) technically results in undefined behaviour. Look into a loop to read and discard characters until the first new line character instead.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User Kernelpanic's Avatar
    Join Date
    Sep 2018
    Location
    Berlin
    Posts
    105
    Quote Originally Posted by laserlight View Post
    Kernelpanic: gets is inherently vulnerable to buffer overflow. You must never use it. Consider alternatives like fgets and scanf with %s and a field width instead.
    @laserlight - I know, but I am a bad boy. Yeah that's right! The input with 'gets' is more simple. In the next version fgets and sscanf like so - below Moeglichkeit 3:
    Rheinwerk Computing :: C von A bis Z &ndash; 4 Formatierte Ein-/Ausgabe mit »scanf()« und »printf()«

    Also, note that fflush(stdin) technically results in undefined behaviour. Look into a loop to read and discard characters until the first new line character instead.
    Yes, fflush is for rest of input like '\n' and also simple.
    Ok, thanks for your tips.

    I use the programming in C as relaxtion and for diversion - or so.
    Have a nice weekend.

  12. #12
    Registered User Kernelpanic's Avatar
    Join Date
    Sep 2018
    Location
    Berlin
    Posts
    105
    Quote Originally Posted by Kernelpanic
    //Allacation of the adresses of both structures
    //Zuweisung der Adressen der beiden Strukturen
    zgr_w1 = &wagen1;
    zgr_w2 = &wagen2;
    It is an allocation of the address of the structure with two variables. Sorry.

  13. #13
    Registered User Kernelpanic's Avatar
    Join Date
    Sep 2018
    Location
    Berlin
    Posts
    105
    Quote Originally Posted by laserlight View Post
    Kernelpanic: gets is inherently vulnerable to buffer overflow. You must never use it. Consider alternatives like fgets and scanf with %s and a field width instead.

    Also, note that fflush(stdin) technically results in undefined behaviour. Look into a loop to read and discard characters until the first new line character instead.
    With fgets it is well, "scanf" with %s and a field width I still don't understand. Instead of fflush(stdin) now with getchar() but in the output the text line will wrap.

    Code:
    //Daten einlesen - Input data
        printf("\nFirma    : ");
        fgets(wagen1.firma, MAX, stdin);
        printf("Modell   : ");
        fgets(wagen1.modell, MAX, stdin);
        
        printf("Anzahl PS: ");        
        do {scanf("%f", &wagen1.ps);} while(getchar() != '\n' && getchar() != EOF);
            printf("Preis    : ");    
        do {scanf("%f", &wagen1.preis);} while(getchar() != '\n' && getchar() != EOF);
            
        printf("\nFirma    : ");
        fgets(wagen2.firma, MAX, stdin);
        printf("Modell   : ");
        fgets(wagen2.modell, MAX, stdin);
        
        printf("Anzahl PS: ");
        do {scanf("%f", &wagen2.ps);} while(getchar() != '\n' && getchar() != EOF);    
        printf("Preis    : ");
        do {scanf("%f", &wagen1.preis);} while(getchar() != '\n' && getchar() != EOF);
    And this loop works once only.

    Code:
    //Daten einlesen
        printf("\nFirma    : ");
        fgets(wagen1.firma, MAX, stdin);
            
        printf("Modell   : ");
        fgets(wagen1.modell, MAX, stdin);
        
        printf("Anzahl PS: ");
        scanf("%f", &wagen1.ps);
    
    
        printf("Preis    : ");
        scanf("%f", &wagen1.preis);
        
        int c;
        do    
            c = getchar();
        while(c != '\n' && c != EOF);
    With loop:
    Structures on functions-schleife-statt-fflush-jpg

    Line wrap:
    Structures on functions-text-umgebrochen-jpg

  14. #14
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Note that fgets keeps the new-line character, which means it is your responsibility to remove it.

    %s won't allow for input with spaces in it, so if you wanted that (and it looks like you do!) you would need to use a scanset instead (again with a length given).
    Code:
    scanf("%79[^\n]", wagen1.modell);
    where the number is one less than the size of the character array (to allow for the \0 character).

  15. #15
    Registered User Kernelpanic's Avatar
    Join Date
    Sep 2018
    Location
    Berlin
    Posts
    105
    Quote Originally Posted by tabstop View Post
    Note that fgets keeps the new-line character, which means it is your responsibility to remove it.

    %s won't allow for input with spaces in it, so if you wanted that (and it looks like you do!) you would need to use a scanset instead (again with a length given).
    Code:
    scanf("%79[^\n]", wagen1.modell);
    where the number is one less than the size of the character array (to allow for the \0 character).
    Thanks for the tip. But it work once only, if twice and more then it comes to an error. Without fflush(stdin) as well. Only errors so or so.

    Microsoft write about fflush(): "fflush on input stream is an extension to the C standard"
    fflush

    Will MS offer a function whose behavior is unclear (for Windows systems)? I will hope no!

    The tip twice:
    Structures on functions-autost-einmmal-jpg

    Once only is OK:
    Structures on functions-autost-einmmal2-jpg

    The code for that:
    Code:
    //Daten einlesen - Input data
        printf("\nFirma    : ");
        //scanf("%49[^\n]", wagen1.firma);
        fgets(wagen1.firma, sizeof(wagen1.firma), stdin);
        printf("Modell   : ");
        //fgets(wagen1.modell, sizeof(wagen1.modell), stdin);
        scanf("%49[^\n]", wagen1.modell);
        
        printf("Anzahl PS: ");
        scanf(" %f", &wagen1.ps);
        //do {scanf("%f", &wagen1.ps);} while(getchar() != '\n' && getchar() != EOF);
        printf("Preis    : ");
        scanf(" %f", &wagen1.preis);
        //do {scanf("%f", &wagen1.preis);} while(getchar() != '\n' && getchar() != EOF);
        fflush(stdin);
                
        printf("\nFirma    : ");
        fgets(wagen2.firma, sizeof(wagen2.firma), stdin);
        printf("Modell   : ");
        fgets(wagen2.modell, sizeof(wagen2.modell), stdin);
        
        printf("Anzahl PS: ");
        scanf(" %f", &wagen2.ps);
        //do {scanf("%f", &wagen2.ps);} while(getchar() != '\n' && getchar() != EOF);
        printf("Preis    : ");
        scanf(" %f", &wagen2.preis);
        //do {scanf("%f", &wagen1.preis);} while(getchar() != '\n' && getchar() != EOF);
        fflush(stdin);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Structures and Functions
    By r895 in forum C++ Programming
    Replies: 3
    Last Post: 04-25-2014, 01:55 PM
  2. help me with structures using functions
    By magnetpest2k7 in forum C Programming
    Replies: 2
    Last Post: 10-07-2009, 01:32 AM
  3. Functions in Structures
    By pritin in forum C++ Programming
    Replies: 1
    Last Post: 03-26-2007, 01:40 AM
  4. functions and structures
    By subflood in forum C Programming
    Replies: 2
    Last Post: 06-11-2005, 06:15 PM
  5. structures and functions
    By student2005 in forum C++ Programming
    Replies: 1
    Last Post: 10-16-2003, 04:12 PM

Tags for this Thread