Thread: printing a 2d array

  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    38

    printing a 2d array

    i used a 2d array to save a string of characters in each row.

    insert
    Code:
    char arr[5][5] = {"hello", "world", "barcelona", "pakistan", "computer"};
    in order to print only one of the words, what can i do?

    and if i want to print all of the words the i have to use a nested loop???

  2. #2
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    693
    Remember that array starts at 0 and goes to N-1. Strings also end in a terminating character '\0', in other words, your second subscript needs to allocate enough space for the largest string + 1 for the null character, and in your case should be arr[5][10]
    Last edited by camel-man; 01-27-2012 at 11:36 PM.

  3. #3
    Registered User
    Join Date
    Oct 2010
    Posts
    132
    Hi, ueg1990. After making the change that camel-man told you about, you can print a word of the array with arr[x] (using %s in printf()), where x goes from 0 to 4.

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 array
    By taurus in forum C Programming
    Replies: 6
    Last Post: 09-04-2008, 06:35 AM
  3. printing array
    By Cpro in forum C++ Programming
    Replies: 7
    Last Post: 03-21-2008, 09:47 AM
  4. printing array
    By publikum in forum C++ Programming
    Replies: 2
    Last Post: 11-16-2004, 04:01 PM
  5. printing to an array
    By zmerlinz in forum C Programming
    Replies: 12
    Last Post: 04-29-2003, 07:48 AM