Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to declare array of arrays? 1

Status
Not open for further replies.

hstijnen

Programmer
Nov 13, 2002
172
NL
Hi,

I want to declare an array of integer arrays of variable length. I thought it must be possible as follows:
int* opt[59];
opt[1] = {1,7,11,0};
opt[2] = {2,7,11,0};
......
opt[58] = {6,9,12,13,15,17,0};

but this causes a compilation error.
What's wrong?
 
Standard ANSI-C doesn't support such aggregate initialisers.

However, if you have GCC3.x, then you should be able to do this.
Code:
#include <stdio.h>

int main ( ) {
  int* opt[59];
  static int opt0[] = { 0, 1, 2, 3, 4, 5, 6 };

  opt[0] = opt0;  /* ANSI-C standard way */
  opt[1] = (int[]){1,7,11,0}; /* GCC supported extension */

  printf("%d %d\n", opt[0][0], opt[1][0] );
  return 0;
}


--
 
Thanks.
With me, (int[]){1,7,11,0}; doesn't work.

Now I shall do:
int opt[59][7] =
{ 1, 7,11, 0, 0, 0, 0, 2, 7,11, 0, 0, 0, 0, ....
 
You can't use {} to assign values to an array unless you do it on the declaration line. So this is valid:

int opt[]={6,32,58,324,7};

But this is not:

int opt[5];
opt={25,67,8,3,36};

Since you want your subarrays to be of variable length, you need to allocate the memory yourself for each subarray, and assign the values in each subarray individually.

Dennis
 
> int opt[59][7] =
> { 1, 7,11, 0, 0, 0, 0, 2, 7,11, 0, 0, 0, 0, ....
If you're going to bite the bullet and just allocate the space depending on the maximum length of a row, then you'll find this useful for eliminating a lot of zeros (and a lot of counting)

Code:
int opt[59][7] ={
  { 1, 7, 11 },  // compiler adds 4 zeros for you
  { 2, 7, 11, 12 }, // compiler adds 3 zeros for you
};
This is extra useful if you later decide that 7 isn't enough.

--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top