Thread: two dim table of char*

  1. #1
    Registered User
    Join Date
    Aug 2002
    Posts
    351

    two dim table of char*

    Hi All,

    Can someone tell me if this is the correct way to create, reference and allocate mem for this data?

    Code:
    int main()
    {
    	char *char_table[2][1];
    
    	char_table[0][0] = strdup("a string in pos 0,0");
    	char_table[0][1] = strdup("a string in pos 0,1");
    
    	char_table[1][0] = strdup("a string in pos 1,0");
    	char_table[1][1] = strdup("a string in pos 1,1");
    }
    Although this works, it's causing memory problems in a bigger program.

    Many thanks,

    rotis23

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Code:
    int main()
    {
    	char *char_table[2][1];
    
    	char_table[0][0] = strdup("a string in pos 0,0");
    	char_table[0][1] = strdup("a string in pos 0,1"); // out of bounds
    
    	char_table[1][0] = strdup("a string in pos 1,0");
    	char_table[1][1] = strdup("a string in pos 1,1"); // out of bounds
    }
    use
    Code:
    char *char_table[2][2];
    Kurt

  3. #3
    Registered User
    Join Date
    Aug 2002
    Posts
    351
    Yes - I have that correct in my other code :/

    Is the remaining code valid?

  4. #4
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Yes the code is valid, but you have to free the memory returned by strdup at some point
    Kurt

  5. #5
    Registered User
    Join Date
    Aug 2002
    Posts
    351
    Thanks for your help Kurt.

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Why bother with the strdup (which isn't an ANSI function anyway)

    Code:
    char *table[2][2] = {
      { "this", "is" },
      { "a", "table" },
    };
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Writing array, to file
    By zootreeves in forum C Programming
    Replies: 9
    Last Post: 09-08-2007, 05:06 PM
  2. progarm doesnt compile
    By kashifk in forum Linux Programming
    Replies: 2
    Last Post: 10-25-2003, 05:54 PM
  3. extra word printing
    By kashifk in forum C++ Programming
    Replies: 2
    Last Post: 10-25-2003, 04:03 PM
  4. inputting words from a file
    By kashifk in forum C++ Programming
    Replies: 5
    Last Post: 10-24-2003, 07:18 AM
  5. help with operator <
    By kashifk in forum C++ Programming
    Replies: 1
    Last Post: 10-21-2003, 03:49 PM