#need C help
4 messages in this thread
Hello fellow Amigan's,
I have a question about C arrays if one of you advanced types could give
me a hand, I would greatly appreciate it.
In basic, if I wanted to load an array of lets say 100 elements, I could
try FOR n = 1 to 100:READ a$(n)
NEXT n
DATA etc,etc…
My question is..Does anyone know of a similar way to mimic the read/data
functions of basic in C? The way I see it now I will have to assign each
element of array a$ separately. A wonderful task considering I really want
to assign a couple thousand in multi-dimensional form.
I'm using the latest (I hope) Aztec C compiler. Your input would be
truely appreciated.
{ Henry }
Henry, if I understand you correctly, you want to "initialize" a large
multi-dimensional array with data known at compile-time. You don't
want to read the data from a diskfile, you want it to be in your
program code.
That means you use:
int ar[100] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11,12,13,14,15,16,17,18,19, 20 …
… ,93,94,95,96,97,98,99,100} ;
if you wanted to initialize ar to be an array of counting numbers and didn't
like loops.
If you wanted:
1 6 8
7 4 2
3 9 5
in a 3 x 3 array, you'd have:
int ar[3][3] { 1, 6, 8, 7, 4, 2, 3, 9, 5} because C arrays are stored
in Row Major Order.
I'd recommend initializing the 3 x 3 array as:
int ar[3][3] {
{ 1, 6, 8 },
{ 7, 4, 2 },
{ 3, 9, 5 }
};
since this way it is much easier to read and to see what the programmer
intended in his code.
— Mike Roth
Have you ever looked at static initialization? Try:
static int Array[] = {0,1,2,3,4,5,6,7,8,9};
This creates an array of 10 integers initialized to 0..9. Also, keep in
mind that variables declared inside functions without the static keyword
are allocated on the stack, while static variables and variables declared
outside functions aren't. An array of 100 ints takes 400 bytes, which uses
a good chunk of your stack space, and takes some time to initialize every
time you enter the function. The larger the array gets, the worse it gets.
So, in most cases, you want to declare large arrays outside of a function,
or as static variables, or both.