[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Need Orca/C help...



In article <eg58451@pro-scat.cts.com> Sean Eller writes:
>I'm working on a project that uses arrays and I wanted to clear the array
>to zero after intializing it.  So this is the code I was using:
>int array[100] [100];
>unsigned x;
>unsigned y;

>for (y = 0; y < 100; ++y)
>        {
>        for (x = 0; x < 100; ++x)
>                array[y][x] = 0;
>        {

The simplest way is to just do this:
int array[100][100] = {0};

This initializes the array position (0,0) to zero and in the docs, it also says
that all array positions not intialized along with the declaration initialization
also gets set to zero, so this is the simplest way.

>It works fine but takes forever.  I looked in the manual and it says I can

Well in my computer science courses, analysis of this algorithm says it
takes O(n^2) time so a 100 by 100 array has 10000 elements. Interesting
isn't it? :)

>use the function calloc to do the same thing and it will clear the memory
>with zeros automatically.  My question is:  How would I use the above
>example with calloc and then access the array at a later time?  I think it
>uses pointers but I'm not sure of how to write or read from the array.
>Before if I wanted to write or read it would simply be this:
>array[5][10] = 1
>or getvalue = array[5][10]

Well, actually, arrays and pointers are the same thing just that C, unlike
Pascal, lets you see it the way it is.  The difference comes from what kind
of code you write to access them.  Well using calloc it would be:

int *array;
array = (int *) calloc(100 * 100, sizeof(int));

then you access it like any other array:

array[5][10] = 1
getvalue = array[5][10]

Just don't forget to do a free(array) to dispose of the memory the pointer is
using after you're done.

BTW, you can do this with any pointer, it's just not efficient. That's where
pointer math comes in, but (hint, hint :) it's something you should look at.

I don't suggest using calloc nor malloc calls unless you know what you're
doing and you're writing really weird code. The simple initialization during
the declaration of the array should be just fine.

>Thanks...

It should work.

>----
>ProLine:  seane@pro-scat
>Internet: seane@pro-scat.cts.com
>UUCP:     crash!pro-scat!seane
>America Online:  tacheon@aol.com

Joseph
--
jlee@bonnie.ics.uci.edu  | Onion (gravity) rings are | Temporal distortion is
                         | the fabric of space.      | just your imagination.