Thread: Dynamic allocation for array of pointers to char

  1. #1
    Awesomefaceradcore bivhitscar's Avatar
    Join Date
    Apr 2006
    Location
    Melbourne, Australia
    Posts
    210

    Unhappy Dynamic allocation for array of pointers to char

    Enter a number of students in a group as a command-line argument. Allocate memory for two arrays: one is the array of pointers to char to store students’ names, and another - an array of integers to store the results (from 0 to 100). Read the names and results from the keyboard and fill in the arrays. Find and display on the screen a name and a mark for students who have the lowest and the highest mark.
    Well, I've been trying to do this for the last couple of days and I just can't figure it out.

    Here's what I have so far:

    Code:
    int main(int argc, char *argv[])
    {
        char * students;            // ? - 'char *students[]'
        int * scores;
        int num, i;
        int max = 0, min = 0, min_i, max_i;
        
        num = atoi( argv[1] );
        
        if ( num <= 0 )
        {
             printf("Please enter a number of students.\n");
             exit(0);
        }
        
        students = (char *) malloc( num * 15 * sizeof( char ) );
        scores = (int *) malloc( num * sizeof( int ) );
        
        for ( i = 0; i < num; i++ )
        {
            printf("Enter the student's name: ");
            gets( &students[i] );            // I know this is wrong, due to the declaration
            
            printf("Enter this student's score: ");
            scanf("%d", &scores[i] );
            fflush( stdin );
            
            printf("\n");
        }
        
        free(students);
        free(scores);
        
        
        system("PAUSE");	
        return 0;
    }

    * I am just making the assumption that each name will be no more than 14 characters long


    As you can probably see from my highlighting, I can tell where my problems are - but it's a catch 22. If I declare an array of pointers to char in the beginning, I need to define a number of pointers the array will hold. But if I just declare a char pointer, when I malloc - it's just one chuck of memory. When indexed as an array, it will not be able to store a string, only a single char (per index).

    Basically, my question is; is there any way to do this, other than reading in each character using getchar() and then appending my own null character at the end of each name?

    Hopefully that all made sense.
    it's ironic considerate rarity patron of love higher knowledge engulfs me...

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(int argc, char *argv[])
    {
      char  **students; /* one is the array of pointers to char to store students’ names */
      int * scores;     /* an array of integers to store the results */
      int num, i;
    
      if ( argc > 1 ) {
        num = atoi( argv[1] );
      } else {
        printf("Please enter a number of students.\n");
        exit(0);
      }
    
      if ( num <= 0 )
      {
        printf("Please enter a number of students.\n");
        exit(0);
      }
    
      students = malloc( num * sizeof *students );
      scores =   malloc( num * sizeof *scores );
    
      for ( i = 0; i < num; i++ )
      {
        char buff[BUFSIZ];
        printf("Enter the student's name: ");
        fgets( buff, BUFSIZ, stdin ); /* NEVER use gets */
    
        students[i] = malloc ( strlen(buff) + 1 );
        strcpy( students[i], buff );
    
        printf("Enter this student's score: ");
        fgets( buff, BUFSIZ, stdin );
        sscanf( buff, "%d", &scores[i] );
      }
    
      for ( i = 0 ; i < num ; i++ ) {
        free( students[i] );
      }
      free(students);
      free(scores);
    
      return 0;
    }
    And read the FAQ on
    - casting malloc
    - using gets
    - using fflush(stdin)
    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.

  3. #3
    Awesomefaceradcore bivhitscar's Avatar
    Join Date
    Apr 2006
    Location
    Melbourne, Australia
    Posts
    210
    I'll have a read through the faqs, but this has me a bit confused:

    Code:
    char buff[BUFSIZ];
    printf("Enter the student's name: ");
    fgets( buff, BUFSIZ, stdin ); /* NEVER use gets */
    I assume you just forgot to declare BUFSIZE?

    Oh, and what should I read to learn more about this line:

    Code:
    char  **students; /* one is the array of pointers to char to store students’ names */
    Last edited by bivhitscar; 05-20-2006 at 02:31 AM.
    it's ironic considerate rarity patron of love higher knowledge engulfs me...

  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
    BUFSIZ is a constant in stdio.h
    Unless you have some brain-damaged fossil compiler.

    > Oh, and what should I read to learn more about this line:
    Maybe this
    http://home.netcom.com/~tjensen/ptr/pointers.htm
    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
    Awesomefaceradcore bivhitscar's Avatar
    Join Date
    Apr 2006
    Location
    Melbourne, Australia
    Posts
    210
    This pointer business is starting to do my head in. I was fine with the basics, but it's starting to get a bit hairy.

    Cheers mate.
    it's ironic considerate rarity patron of love higher knowledge engulfs me...

  6. #6
    Awesomefaceradcore bivhitscar's Avatar
    Join Date
    Apr 2006
    Location
    Melbourne, Australia
    Posts
    210
    Should I point out that strcopy() is bad (yes, I know it won't overflow in this case), or just go back to my learning?
    it's ironic considerate rarity patron of love higher knowledge engulfs me...

  7. #7
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,534
    Quote Originally Posted by bivhitscar
    Should I point out that strcopy() is bad (yes, I know it won't overflow in this case), or just go back to my learning?
    I would imagine that strcpy would work out better for you than strcopy.

    If you are thoughtful when you use strcpy, it should not be a problem. Just remember that the C language won't hold your hand when you are programming with it, but rather it might bite you.

  8. #8
    Awesomefaceradcore bivhitscar's Avatar
    Join Date
    Apr 2006
    Location
    Melbourne, Australia
    Posts
    210
    Oops, I always pronounce it copy - hence the error. *paranoid*

    And yeh, I was just being facetious.
    it's ironic considerate rarity patron of love higher knowledge engulfs me...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  2. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 05:42 PM
  3. Obtaining source & destination IP,details of ICMP Header & each of field of it ???
    By cromologic in forum Networking/Device Communication
    Replies: 1
    Last Post: 04-29-2006, 02:49 PM
  4. Dynamic allocation (I thought it would crash)
    By Baaaah! in forum C Programming
    Replies: 16
    Last Post: 11-30-2005, 05:10 PM
  5. Program Crashing
    By Pressure in forum C Programming
    Replies: 3
    Last Post: 04-18-2005, 10:28 PM