two dimensional array initialization

This is a discussion on two dimensional array initialization within the C Programming forums, part of the General Programming Boards category; Hello everyone, I find to initialize two dimentional array in Visual Studio, I have to specify the number of elements. ...

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    1,579

    two dimensional array initialization

    Hello everyone,


    I find to initialize two dimentional array in Visual Studio, I have to specify the number of elements. For example,

    Code:
    const char foo[][] = {"hello",  "world"}; // compile error
    const char goo[][64] = {"hello",  "world"}; // compile correct
    So, the best solution is to specify the number of elements of the 2nd dimension (inner dimension)?


    thanks in advance,
    George

  2. #2
    Registered User
    Join Date
    Jun 2007
    Posts
    63
    You should consider using char **string to get an array of strings or char string[][N] for static declaration.

  3. #3
    Registered User
    Join Date
    Jan 2007
    Posts
    330
    Code:
    const char *foo[] = { "1", "2" };

  4. #4
    Chinese pâté foxman's Avatar
    Join Date
    Jul 2007
    Location
    Canada
    Posts
    404
    The best solution depends on what you need the array for.

    Because a solution like this one
    Code:
    char *foo[] = { "1", "2" };
    only allow you to change the value in the array. But you can't modify the string. Example:

    Code:
    	// This is correct
    	foo[0] = foo[1];
    
    	// This is incorrect (will lead to runtime error)
    	foo[0][0] = 'b';
    
    	// These are big no no
    	scanf("%s", &foo[0]);
    	fgets(foo[0], sizeof(foo[0]), stdin);
    But i just saw that you were declaring your variable as const, so i guess this is the way to go.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 08:25 PM
  2. Two Dimensional Array Input from Formatted Data
    By teedoff087 in forum C Programming
    Replies: 14
    Last Post: 04-29-2007, 02:46 AM
  3. Multi dimensional array
    By big146 in forum C++ Programming
    Replies: 4
    Last Post: 06-14-2004, 06:03 PM
  4. 2d arrays in C
    By Unregistered in forum C Programming
    Replies: 6
    Last Post: 04-20-2002, 12:09 PM
  5. Replies: 5
    Last Post: 11-20-2001, 12:48 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21