Thread: Need help printing 2D array

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

    Need help printing 2D array

    ok so for a homework assignment I need to make an inventory system. One of the options I need to create in the menu is to scan in items to a 2D array. This I can do fine, my teacher said to make the array [10][20]. But when I try to print the array, I use a function with a nested for loop, and try to print %c for each character. It compiles, but just prints out (NULL) (NULL) (NULL). Here is the example of my code.


    Code:
    void list_inv(char inv_items[10][20], int inv_count[10])
    {
        int i;
        int j;
    
    
        for(i=0;i<11;i++)
        {
            for(j=0;j<21;j++)
            {
                printf("%c", inv_items[i][j]);
            }
        }      
    }

  2. #2
    Registered User
    Join Date
    Nov 2011
    Location
    Saratoga, California, USA
    Posts
    334
    How do you know your array populated successfully if you all you get is NULL printed out? Paste your whole code? Remember that for an array a[n], the indexes are 0..n-1. inv_items[10][j] and inv_items[i][20] are not valid, yet your for loops are trying to access them.

  3. #3
    Registered User
    Join Date
    Nov 2011
    Posts
    12
    this is my whole code, its no where near done, I just started yesterday. But you will see that in my menu option 2 i try to scan into my 2D array and now that you mention it, im pretty sure it is wrong. I'm sorry if my coding is bad, I'm new to this and its one of the courses im taking in college. But any way, here is my whole code. I commented on anything I didnt know how to do.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    void list_inv(char inv_items[10][20], int inv_count[10]); // Print inventory function
    void inv_delete(int d, char inv_items[10][20]); // Delete item function
    char inv_write(char inv_items[10][20]); // Writes inventory to file
    
    
    int main()
    {
        int menu;
        char inv_items[10][20];
        int inv_count[10];
        int done = 0;
        int d;
        FILE *fw;
        FILE *fr;
    
    
        while(done == 0)
        {
            printf("1. List Inventory\n2. Enter New Item\n3. Enter Number of Items\n4. Delete Item\n");
            printf("5. Write Inventory to File\n6. Read Inventory from file\n7. Exit\n");
    
    
            scanf("%d", &menu);
    
    
            if(menu !=7)
            {
                // Menu Option 1: "List Inventory"
                if(menu == 1)
                {
                    list_inv(inv_items, inv_count);
                }
                // Menu Option 2: "Enter New Item"
                if(menu == 2)
                {
                    printf("Type in the name of the item you would like to add to iventory.\n");
                    scanf("%s", &inv_items[10][20]);
                }
                // Menu Option 3: "Enter Number of Items"
                if(menu == 3)
                {
                    printf("Enter the number of items.\n");
                    scanf("%d", &inv_count[10]);
                }
                // Menu Option 4: "Delete Item"
                if(menu == 4)
                {
                    printf("Enter the row number of the item you would like to delete.\n");
                    scanf("%d", &d);
                    inv_delete(d, inv_items);
                }
                //Menu Option 5: "Write to file"
                if(menu == 5)
                {
                    fw = fopen("inventory.txt", "w");
                    // dont know how to write a 2D array to file
                }
                // Menu Option 6: "Read from file"
                if(menu == 6)
                {
                    //dont know how to read a file and save to a 2D array
                }
                // Precaution if non menu option is entered
                if(menu != 1,2,3,4,5,6)
                {
                    printf("You have entered an incorrect option, please choose a valid option.\n");
                }
            }
            else
            {
                done++;
            }
        }
    }
    void list_inv(char inv_items[10][20], int inv_count[10])
    {
        int i;
        int j;
    
    
        for(i=0;i<11;i++)
        {
            for(j=0;j<21;j++)
            {
                printf("%c", inv_items[i][j]);
            }
        }      //How to do you get items and count to print off simultaneously?
    }
    void inv_delete(int d, char inv_items[10][20])
    {
        int i;
        int j;
    
    
        for(i=d;i<11;i++)
        {
            for(j=0;j<21;j++)
            {
                inv_items[i][j]=inv_items[i+1][j];
            }
        }
    }
    char inv_write(char inv_items[10][20])
    {
        // Dont know how to write a 2D array
    }

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Each row of a 2D char array should be a string, so if int i represents the row counter, and j represents the column counter, then:

    Code:
    void list_inv(char inv_items[10][20], int inv_count[10])
    {
        int i;
        int j;
    
    
        for(i=0;i<11;i++)
        {
                printf("%s", inv_items[i]);
            }
        }      
    }
    Remembering that a string in C is not just a bunch of char's - they MUST have a null char to mark the end of the string: '\0'.

    If you happen to just have a bunch of char's, rather than strings, then you need this:

    Code:
    void list_inv(char inv_items[10][20], int inv_count[10])
    {
        int i;
        int j;
    
    
        for(i=0;i<11;i++)
        {
            for(j=0;j<21;j++)
            {
                printf("%c", inv_items[i][j]);
            }
            printf("\n"); //end of one row  
      }      
    }
    If you have a newline on the end of your rows of chars, then you won't probably want the above to print out the newline at the end of each row. Generally, that is what you want, however.

    For the rest, back in a bit.

  5. #5
    Registered User
    Join Date
    Nov 2011
    Posts
    12
    thanks this is a big help

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Ironed out a few things, but haven't run it.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define ROWS 10
    
    void list_inv(char inv_items[ROWS][20], int inv_count); // Print inventory function
    int inv_delete(char inv_items[ROWS][20], int inv_count); // Delete item function
    int inv_read(char inv_items[ROWS][20]); 
    void inv_write(char inv_items[ROWS][20]); // Writes inventory to file
    
    int main()
    {
        int menu;
        char inv_items[ROWS][20];
        int inv_count=0;
        int done = 0;
    
        while(done == 0)
        {
            printf("1. List Inventory\n2. Enter New Item\n3. Enter Number of Items\n4. Delete Item\n");
            printf("5. Write Inventory to File\n6. Read Inventory from file\n7. Exit\n");
    
    
            scanf("%d", &menu);
    
    
            if(menu !=7)
            {
                // Menu Option 1: "List Inventory"
                if(menu == 1)
                {
                    list_inv(inv_items, inv_count);
                }
                // Menu Option 2: "Enter New Item"
                if(menu == 2)
                {
                    printf("Type in the name of the item you would like to add to inventory.\n");
                    scanf("%s", inv_items[++inv_count]);
                }
                // Menu Option 4: "Delete Item"
                if(menu == 4)
                {
                    printf("Enter the row number of the item you would like to delete.\n");
                    list_inv(inv_items, inv_count);
                    inv_count = inv_delete(inv_items, inv_count);
                }
                //Menu Option 5: "Write to file"
                if(menu == 5)
                {
                    inv_write(inv_items);
                }
                // Menu Option 6: "Read from file"
                if(menu == 6)
                {
                    inv_count = inv_read(inv_items);           
                }
                // Precaution if non menu option is entered
                if(menu != 1,2,3,4,5,6)
                {
                    printf("You have entered an incorrect option, please choose a valid option.\n");
                }
            }
            else
            {
                done++;
            }
        }
    }
    
    
    void list_inv(char inv_items[ROWS][20], int inv_count)
    {
        int i;
         
        for(i=0;i<ROWS;i++)
        {
           printf("%s", inv_items[i]);
        }     
    }
    int inv_read(char inv_items[ROWS][20]) 
    {
       int i=0;
       FILE *fp;
       if((fp=fopen("inventory.txt", "r")) == NULL) { 
          printf("\nError: unable to open inventory file!\n");
          return 0;
       }
       while((fgets(inv_items[i], 20, fp)) != NULL)
       {
          ++i;
       }     
       fclose(fp);
       return i;
    }
    
    
    void inv_write(char inv_items[ROWS][20])
    {
       int i;
       FILE *fp; 
       if((fp=fopen("inventory.txt", "w")) == NULL) { 
          printf("\nError: unable to open inventory file!\n");
          return;
       }
     
       for(i=0;i<ROWS;i++)
       {
          fprintf(fp, "%s", inv_items[i]);
       }     
       fclose(fp);
    }
    
    int inv_delete(char inv_items[ROWS][20], int inv_count)
    {
       int i;
       char again='y';
       printf("\n");
       while(again=='y' || again=='Y') {
          printf("Which row number do you want to delete? ");
          scanf("%d", &i);
          getchar();
          if(i >= 0 && i < ROWS) 
          {
             inv_items[i][0]='\0';
             --inv_count;
          }
          else 
             printf("\nThat is an invalid row number. Please specify another.\n\n");
    
          printf("Delete another item? [y/n]: ");
          scanf("%c", &again);
          getchar();
          printf("\n");
    
       }
    
       return inv_count;
    }
    The variable inv_count is going to get slaughtered, so don't rely on it in your program. Pretty much just there for looks. Why? Because there is no way of "compacting" your inventory array. After #7 gets deleted, if you depend on the inv_count, your listing and printing to file, will cut off the last items (inv_items[9]).

  7. #7
    Registered User
    Join Date
    Nov 2011
    Posts
    12
    This is a huge help, thanks so much!

  8. #8
    Registered User
    Join Date
    Nov 2011
    Posts
    12
    the only problem is I need option 3. You have it listed in the menu but then skip it in the if statements. So when you select option 3, you get an invalid option choice

  9. #9
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    << Dammit! Schwindy noticed! >>

    I didn't know if #3 was for adding items, or deleting them. I added that functionality, into the deletion function, instead. What was #3 originally going to be used for?
    Last edited by Adak; 11-20-2011 at 04:10 PM.

  10. #10
    Registered User
    Join Date
    Nov 2011
    Posts
    12
    separate functions, 2. adds an item and 3. is to choose how many are to be added or to change the amount (i.e. if I had 5 apples and sold 2, I would change the stock from 5 to 2 without having to completely delete and re-enter the item)

  11. #11
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    This is the old code for #3. It can't work because the array has no index beyond 9 (a 10 element array is indexed from 0 - 9 only).

    So what do you want to do here?

    Code:
                // Menu Option 3: "Enter Number of Items"
                if(menu == 3)
                {
                    printf("Enter the number of items.\n");
                    scanf("%d", &inv_count[10]); //<<-- out of range
                }

  12. #12
    Registered User
    Join Date
    Nov 2011
    Posts
    12
    ya thats because I can only have 10 strings stored in my inventory, inv_items[10][20], each item gets a number for inventory based upon their element. so if i store socks into my inventory first, I should the store the number of socks i have in the inv_count using option 3 after. the whole program is dumb cause this assignment for class is supposed to be an exercise

  13. #13
    Registered User
    Join Date
    Nov 2011
    Posts
    12
    also the code you posted early has errors when run, it doesnt scan in right. when i run option 2, i type in what i want to store to inventory, and then it prints invalid option choice

  14. #14
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I can't test the code without having the specifications of the input, etc. I can compile it, but not test it without knowing what the input should be like.

    Do you want it like:

    id number description quantity in stock price per unit ?

    Can you post an example of the input file you will have or want to create?

    When you say "delete an item", do you mean it has one less quantity in stock, or the entire stock item has been removed (pulled from stock)?

  15. #15
    Registered User
    Join Date
    Nov 2011
    Posts
    12
    whole item gets deleted. For option 2 I input a name of an item (i.e. socks, shirt, etc.). Option 3 gets the stock of the item put in, and it can also change the stock of an existing item.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Printing an array of strings until array == NULL
    By mikemhz in forum C Programming
    Replies: 10
    Last Post: 11-04-2011, 01:09 PM
  2. Printing an array
    By LoveTractor in forum C Programming
    Replies: 5
    Last Post: 11-21-2010, 04:26 PM
  3. Printing 2D Array
    By BB89 in forum C Programming
    Replies: 11
    Last Post: 11-16-2009, 05:33 AM
  4. printing array
    By Cpro in forum C++ Programming
    Replies: 7
    Last Post: 03-21-2008, 09:47 AM
  5. Printing a 2D array
    By Suchy in forum C++ Programming
    Replies: 2
    Last Post: 11-10-2007, 04:53 PM

Tags for this Thread