Thread: Enter n number of persons (Structs, pointers, memory allocation)

  1. #1
    Registered User
    Join Date
    Feb 2013
    Location
    Sweden
    Posts
    171

    Question Enter n number of persons (Structs, pointers, memory allocation)

    Hi! Entering that it will just add one person works fine, but not for two. When entering the name of the second person the program crashes?

    I haven't been doing structs, pointers and memory allocation much so could someone explain why the program crashes and which lines of my code that are incorrect.

    1. Add n number of persons (entered amount of persons)
    2. Print the list of persons entered to the console window

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    struct Person {
        char* name;
        int birthYear;
        int phoneNumber;
        
        // Salary per month
        float salary;
    };
    
    
    // Add a person
    struct Person addPerson(struct Person *person, int amountOfPersons);
    
    
    // Print all persons in register
    void printPersons(struct Person *person, int amountOfPersons);
    
    
    // Print the youngest- or oldest person
    
    
    // Print the person with lowest- or highest salary
    
    
    // Staff cost per month
    
    
    // Search for a person by typing the name
    
    
    // Remove undesirable staff
    
    
    int main(int argc, char** argv) {
        
        int amountOfPersons;
        
        printf("Enter number of persons to add: ");
        scanf("%d", &amountOfPersons);
        
        // Calculate storage for n amount persons
        struct Person* person = (struct Person*)malloc(sizeof(struct Person) * amountOfPersons);
        
        addPerson(person, amountOfPersons);
        printPersons(person, amountOfPersons);
        
        free(person);
        
        return 0;
    }
    
    
    struct Person addPerson(struct Person *person, int amountOfPersons) {
        
        int i = 0; 
        while (i < amountOfPersons) {
            
            printf("\n --- Add a person ---");
        
            printf("\nName: ");
            scanf("%s", person[i].name);
        
            printf("\nBirth year: ");
            scanf("%d", &person[i].birthYear);
        
            printf("\nPhone number: ");
            scanf("%d", &person[i].phoneNumber);
        
            printf("\nSalary: ");
            scanf("%f", &person[i].salary);
            
            i++;
        }
        
        return *person;
    }
    
    
    
    
    void printPersons(struct Person *person, int amountOfPersons) {
        
        int i = 0;
        while (i < amountOfPersons) {
            printf("\nName: %s", person[i].name);
            printf("\nBirth year: %d", person[i].birthYear);
            printf("\nPhone number: %d", person[i].phoneNumber);
            printf("\nSalary: %f", person[i].salary);
            i++;
        }
        
    }

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,729
    You don't allocate additional memory for the person's name. It's a miracle it runs even once!...

    Either make that member a static array or call malloc for it before scanf.
    Last edited by GReaper; 12-06-2017 at 01:15 PM.
    Devoted my life to programming...

  3. #3
    Banned
    Join Date
    Aug 2017
    Posts
    861
    oh should I show you a fast way without malloc? and yes GReaper is correct their is a thing you got a do if you're going to use char pointer in lue of char var[100];

  4. #4
    Registered User
    Join Date
    Feb 2013
    Location
    Sweden
    Posts
    171
    This crashes too, so I guess that is not how you meant?
    And what do I need to do to use a char pointer?

    Wait there is a fast way to enter n persons without malloc and
    using an array of for example 100 elements?

    Code:
        
        int amountOfPersons;
        printf("Enter number of persons to add: ");
        
        // Calculate storage for n amount persons
        struct Person* person = (struct Person*)malloc(sizeof(struct Person) * amountOfPersons);
        scanf("%d", &amountOfPersons);
        
        addPerson(person, amountOfPersons);
        printPersons(person, amountOfPersons);
        
        free(person);
    Last edited by DecoratorFawn82; 12-06-2017 at 01:41 PM.

  5. #5
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,729
    Nonono, I meant inside your addPerson() function.
    Devoted my life to programming...

  6. #6
    Banned
    Join Date
    Aug 2017
    Posts
    861
    Quote Originally Posted by DecoratorFawn82 View Post
    This crashes too, so I guess that is not how you meant?
    And what do I need to do to use a char pointer?

    Wait there is a fast way to enter n persons without malloc and
    using an array of for example 100 elements?
    ok you asked, so I show. Also shows two ways for this char thing 1. char *pointer, and 2. char var[50]; just need to look to see it. I am kind of reluctant to post everything GReaper was helping you, but this is just not complete if I remove some of it. I know, I'll just pull a "Oh well"
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    // to get inout off command line and 
    //put it into a struct array
    //fprintf to file.
    //then read and print back file
    
    typedef struct Accounts
    {
        char fristName[50];
        char *lastName;
        int IDNumber;
        float decimal_point_number;
    }account;
    
    
    int main (int argc, const char **argv)
    {
        if (argc < 2)
        {
            printf("no outfile specified\n");
            return -1;
        }
        FILE *outfile;
        
        if ( (outfile = fopen(argv[1], "w+")) == NULL )
        {
            printf("File < %s > Not Able to be Opened\n", argv[1]);
            return -1;
        }
        
        char buffer[1024];
        char Fname[50], Lname[50];
        int id = 0;
        float dpn = 0.0;
        int newRecords = 0, i = 0;
        
        printf("Amount of new records needed?\n");
        scanf(" %d", &newRecords);
        
        account newAccounts[newRecords];
        
        memset(newAccounts, 0, newRecords * sizeof(account));
        
        while (  i < newRecords)
        {
            printf("Add Frist name Last Name Id, decimal point number\n");
            getchar(); 
            
            fgets(buffer, sizeof buffer, stdin);
            sscanf(buffer, "%s%s%d%f", Fname,Lname,&id,&dpn);
            
            // The part where you do that special thing to get char's to work 
           // removed intentionally. 
          // now the rest of the stuff
          
            newAccounts[i].IDNumber = id;
            newAccounts[i].decimal_point_number = dpn;
            i++;    
            printf("\n\nRecord %d gotten\n"
            "%d Left to go \n",i, ( newRecords - i));
        }
        
        for (size_t a = 0; a < sizeof(newAccounts)/sizeof(newAccounts[0]); a++)
            fprintf(outfile, "Name %s %s ID %d some Decimal Number %.2f\n", newAccounts[a].fristName,
            newAccounts[a].lastName,newAccounts[a].IDNumber,newAccounts[a].decimal_point_number);
            
        for (size_t a = 0; a < sizeof(newAccounts)/sizeof(newAccounts[0]); a++)
            printf("Name %s %s ID %d some Decimal Number %.2f\n", newAccounts[a].fristName,
            newAccounts[a].lastName,newAccounts[a].IDNumber,newAccounts[a].decimal_point_number);
        
        
        fclose(outfile);
        
    return 0;    
    }
    use it how ever you want.
    Last edited by userxbw; 12-06-2017 at 02:42 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Structs, Pointers, Memory Allocation, Stacks
    By CodeTheLoad in forum C Programming
    Replies: 1
    Last Post: 10-03-2016, 07:47 AM
  2. CS assignment with dynamic structs and memory allocation
    By arbitraryproc in forum C Programming
    Replies: 4
    Last Post: 10-21-2012, 05:35 PM
  3. problem with memory allocation and structs
    By Durango2011 in forum C Programming
    Replies: 0
    Last Post: 12-04-2011, 04:36 AM
  4. Structs and dynamic memory allocation
    By PaulCocaine in forum C Programming
    Replies: 3
    Last Post: 11-22-2010, 10:14 AM
  5. Memory Allocation and Structs
    By reversaflex in forum C Programming
    Replies: 7
    Last Post: 04-04-2008, 02:46 PM

Tags for this Thread