www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Simple Array Question

reply Silv3r <14908832 sun.ac.za> writes:
When using multi-dimensional arrays I easily get confused as to the order of
the notation. But why does args[i][] equal args[][i] (code below)? I assume
args[i][] is the more correct version as only args[i][0] gives the correct
results?

-Silv3r

-----------------------------------------------------------------------
import std.stdio;

void main(char[][] args)
{
 writefln("args.length = %d\n", args.length);
 for (int i = 0; i < args.length; i++)
 {
  if(args[i][] == args[][i]) // why does args[i][] equal args[][i]?
   writefln("Why does this work? [%d] = '%s'", i, args[i][]);
  writefln("<%s>,<%s>", args[i][0],args[0][i]);
 }
}
-----------------------------------------------------------------------
Jun 01 2007
next sibling parent Johan Granberg <lijat.meREM OVEgmail.com> writes:
Silv3r wrote:

 When using multi-dimensional arrays I easily get confused as to the order
 of the notation. But why does args[i][] equal args[][i] (code below)? I
 assume args[i][] is the more correct version as only args[i][0] gives the
 correct results?
 
 -Silv3r
 
 -----------------------------------------------------------------------
 import std.stdio;
 
 void main(char[][] args)
 {
  writefln("args.length = %d\n", args.length);
  for (int i = 0; i < args.length; i++)
  {
   if(args[i][] == args[][i]) // why does args[i][] equal args[][i]?
    writefln("Why does this work? [%d] = '%s'", i, args[i][]);
   writefln("<%s>,<%s>", args[i][0],args[0][i]);
  }
 }
 -----------------------------------------------------------------------
ok, first args[] is the same as writing only args as a slice of an entire dynamic array is itself. second think of the array brackets as a stack (char[])[] args so args is an array (of char arrays) if you take an element of that you eliminate the outer brackets char[] a=args[0]; hope this helps and if I misunderstood the question I'm sorry.
Jun 01 2007
prev sibling parent reply BCS <ao pathlink.com> writes:
Reply to Silv3r,

 When using multi-dimensional arrays I easily get confused as to the
 order of the notation. But why does args[i][] equal args[][i] (code
 below)? I assume args[i][] is the more correct version as only
 args[i][0] gives the correct results?
 
 -Silv3r
 
 if(args[i][] == args[][i]) // why does args[i][] equal args[][i]?
args[i][] == get args[i], take all of it as a slice args[][i] == get all of args as a slice, take [i] of it in an expression [] is the same as [0..$]
Jun 01 2007
next sibling parent BCS <ao pathlink.com> writes:
Reply to BCS,

This reminds me of something I have been finding handy recently:

//take a slice starting at i and of length j:
arr[i..$][0..j]

the alternative is a bit uglier IMHO

arr[i..i+j]
Jun 01 2007
prev sibling parent Silv3r <14908832 sun.ac.za> writes:
Thanks, now I understand arrays a bit better!
Jun 01 2007