[prog] mutlitdimensional arrays in C

Jenn Vesperman jenn at anthill.echidna.id.au
Sun Oct 10 12:02:47 EST 2004


On Sun, 2004-10-10 at 01:17, aec wrote:

> > The thing is, you declared your return type as "int" and what you try to
> > return is n, which you declared as type int[5][4]. Hence the error :
> > int[5][4] is, as I told before, a pointer. So you are doing exactly what
> > gcc suggests to you : it waits an integer and you give him a pointer.
> 
> Yep, I see now whats going on, I did just what you said and it
> compiles now with the function type void and no return.
> 
> I have to do structures next then pointers so it will be a while :) 

structs also use implied pointers. :)

Short form of a 'what is a pointer' discussion:

A memory block that contains a value of '5' would look like this

---
|5|
---

However, a memory block that contains a pointer would look like this

---------
|address|
---------


And the address points to a memory block that contains a value of '5'
(or whatever)

---------        ---
|address| -----> |5|
---------        ---


So an array is actually a pointer, because it's this

----------------
|array variable|
----------------
       |
   -----
   |
   V
-------------------------------------
|item 1|item 2|item 3|item 4|.....
-------------------------------------


I'm not going to try to ascii-art a multidimensional array!

Structs are pointers, just like arrays. They're a little more
complicated, and I don't want to ascii-art that, either. But you can ask
if you find them unclear.


Now, as for 'casting'. C is a language which assumes that the programmer
is always right, even when she's wrong. If you want to try to add two
characters together, it lets you. Want to try to use a string function
on an integer? It'll let you.
If you have warnings turned on in your compiler, it will tell you that
you're doing this wrong. Just in case you didn't mean to.

If you want to shut the warning up for just the one instance where you
really mean it, you 'cast' the variable, by putting its temporary new
identity in front of it in ()brackets. Like this:

int randomexample()
{
int result;
char alpha='a', beta='b';

result = (int) alpha + (int) beta;
return result;
}


That should return the sum of the ascii values for 'a' and 'b'. Without
a compiler warning.

Note: I didn't test it.
Note2: it's a scarily long time since I last used C. Any errors are
mine.




Jenn V.
-- 
    "Do you ever wonder if there's a whole section of geek culture 
        	you miss out on by being a geek?" - Dancer.
   My book 'Essential CVS': published by O'Reilly in June 2003.
jenn at anthill.echidna.id.au     http://anthill.echidna.id.au/~jenn/




More information about the Programming mailing list