Thread: Printing a 2d array?

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    33

    Printing a 2d array?

    I've been playing around with this program for a bit and the implementation seems to be correct. However, I think I did something wrong when trying to print out the characters of the 2d array. What did I do wrong??

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    #include <limits.h>
    
    
    int main(){
    
        char listWords[10][10]; //10 strings of a maximum of 5 characters each
        char msg[50] = "this is a test"; //now split the msg and put the words in listWords
    
        int column = 0;
        int wordSize = 0;
        int index = 0;
    
        while (msg[index] != '\0') {
            if (msg[index] != ' ') {
                listWords[column][wordSize] = msg[index]; //add character
                wordSize++;
            }else{ //if space is found
                listWords[column][wordSize] = '\0';
                column++;
                wordSize = 0;
            }
        }
    
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                printf("%c ", listWords[i][j]);
            }
            printf("\n");
        }
    
        return 0;
    }

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    You should tell us what is wrong. What output do you get? What output did you expect?

    Why make listWords a 10x10 array if you only have strings of length 5? You should use a constant:
    Code:
    #define MAX_WORDS    10
    #define WORD_LEN    5
    char listWords[MAX_WORDS][WORD_LEN + 1]; // +1 for the null character
    Then, you need to check that constant, and make sure that index never exceeds MAX_WORDS, and wordSize never exceeds WORD_LEN when you're building your word list.

    You never increment index in your while loop.

    Also, you have a bug in your printing for loops, you print all 10 "words", even if there are only 4, and all 10 chars of each word in listWords, no matter how many chars there actually are. This causes a lot of garbage output.

  3. #3
    Registered User
    Join Date
    Feb 2013
    Posts
    33
    I got it. Thank you!

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 array
    By Cpro in forum C++ Programming
    Replies: 7
    Last Post: 03-21-2008, 09:47 AM
  4. Printing Array help
    By saahmed in forum C Programming
    Replies: 18
    Last Post: 02-22-2006, 10:11 PM
  5. array printing help
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 07-10-2002, 01:10 PM

Tags for this Thread