0

Practically, I want to know how to use an array value for another array's size declaration. I have this test-code :

main(){

int sz[3]={1,2,3};

int track1[ sz[0] ]={111};
int track2[ sz[1] ]={222,222};
int track3[ sz[2] ]={333,333,333};

printf("%d %d %d\n", track1[0],track2[1],track3[2]);

}

These are the warnings and errors I get:

test2.c: In function ‘main’:
test2.c:4: error: variable-sized object may not be initialized
test2.c:4: warning: excess elements in array initializer
test2.c:4: warning: (near initialization for ‘track1’)
test2.c:5: error: variable-sized object may not be initialized
test2.c:5: warning: excess elements in array initializer
test2.c:5: warning: (near initialization for ‘track2’)
test2.c:5: warning: excess elements in array initializer
test2.c:5: warning: (near initialization for ‘track2’)
test2.c:6: error: variable-sized object may not be initialized
test2.c:6: warning: excess elements in array initializer
test2.c:6: warning: (near initialization for ‘track3’)
test2.c:6: warning: excess elements in array initializer
test2.c:6: warning: (near initialization for ‘track3’)
test2.c:6: warning: excess elements in array initializer
test2.c:6: warning: (near initialization for ‘track3’)
test2.c:8: warning: incompatible implicit declaration of built-in function ‘printf’

What's the problem here, and ovarall is this even possible, what I've tried ?

sanchez
  • 4,519
  • 3
  • 23
  • 53
k t
  • 343
  • 5
  • 15

2 Answers2

2

When you have an initializer, you can't really have a variable number of elements. Just leave it out and let the compiler count the number of values.

int track1[]={111};
int track2[]={222,222};
int track3[]={333,333,333};

Without an initializer, your code will work in C (using C99 variable-length arrays) and in C++ by adding the constexpr keyword to the declaration of sz.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • I tried using const int sz[] and it did not work...and then I saw your pointer to constexpr. Thanks. – lsk Jul 14 '13 at 00:38
1

Ben has answered the static array question already. The other possibility is to use dynamically allocated arrays. For example

int *track1 = (int *)allocate_int_array(sz[0]);
int *track2 = (int *)allocate_int_array(sz[1]);
int *track3 = (int *)allocate_int_array(sz[2]);

This will give you the option of reading track* array sizes from sz[] as well as using track1, 2 and 3 pointers as arrays in the rest of the code. Ofcourse, freeing and other malloc pitfals apply.

lsk
  • 532
  • 4
  • 5