initializing an array

Started by
5 comments, last by Da cobra 20 years, 1 month ago
why can''t I initialize my array like this char array[pb->max] [16] ; where pb->max is an int inside a structure and pb is a pointer to that structure pb->max is 100 I get the error expected constant expression how can I solve this problem thanx in advance...
Advertisement
you'd need to use pointers, I believe a non-pointer array like you're doing requires constant dimensions so that the compiler can sort it out properly.

Even then, with pointers, I'm not sure if you can do DMA on a 2D array where you only specify the first dimension. To be honest, the way I'd do things:

//definechar *array = new char[ pb->max * 16 ];//usearray[ Y*pb->max + X ] = ...;//deletedelete[] array; 


hth
Jack


[edited by - jollyjeffers on February 22, 2004 6:46:15 AM]

<hr align="left" width="25%" />
Jack Hoxley <small>[</small><small> Forum FAQ | Revised FAQ | MVP Profile | Developer Journal ]</small>

I solved it a bit with a #define

but thanx anyway for your help
You can''t create an array just declaring it like you did if any of it''s dimensions is non-constant. Since the value of pb->max is only known in running time (and not in compile time) you must create the array dynamically, using array = new char[pb->max].

Blew
- blew
Isn''t this changed in the latest C spec? (Note: C not C++)

[ CodeDread ]
Changed in what way? Being able to declare arrays with a variable for it''s size? I doubt it. Unless the declaration is converted to something else by the compiler...

Blew
- blew
quote:Original post by rypyr
Isn''t this changed in the latest C spec? (Note: C not C++)


Yes, C99 supports variable-length array at local scope.

“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.” — Brian W. Kernighan (C programming language co-inventor)
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement