www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - about array setting

reply dfun <boyseeyou gmail.com> writes:
about array setting
on this page http://www.digitalmars.com/d/arrays.html
give an example

int[3] s;
int* p;
s[] = 3;		// same as s[0] = 3, s[1] = 3, s[2] = 3
p[0..2] = 3;		// same as p[0] = 3, p[1] = 3

pring error => Error: Access Violation
why?
use dmd 1.0
Jan 19 2007
next sibling parent Chris Nicholson-Sauls <ibisbasenji gmail.com> writes:
dfun wrote:
 about array setting
 on this page http://www.digitalmars.com/d/arrays.html
 give an example
 
 int[3] s;
 int* p;
 s[] = 3;		// same as s[0] = 3, s[1] = 3, s[2] = 3
 p[0..2] = 3;		// same as p[0] = 3, p[1] = 3
 
 pring error => Error: Access Violation
 why?
 use dmd 1.0

Because 'p' doesn't actually point to anything. It is an incomplete example (one which assumes users will fill in the details). Try something like the following: <code> int[3] s ; int* p ; s[] = 3; // same as s[0] = 3, s[1] = 3, s[2] = 3 p = s.ptr; p[0 .. 2] = 1; // same as p[0] = 1, p[1] = 1 // and, in this case, s[0] = 1, s[1] = 1 </code> -- Chris Nicholson-Sauls
Jan 19 2007
prev sibling parent Bill Baxter <dnewsgroup billbaxter.com> writes:
dfun wrote:
 about array setting
 on this page http://www.digitalmars.com/d/arrays.html
 give an example
 

The examples are assuming you do something like allocate p inbetween the declaration and usage lines.
 int[3] s;
 int* p;

-- need something like p = new int[3]; here.
 s[] = 3;		// same as s[0] = 3, s[1] = 3, s[2] = 3
 p[0..2] = 3;		// same as p[0] = 3, p[1] = 3
 
 pring error => Error: Access Violation
 why?
 use dmd 1.0

It's clear to you that this is an error, right? int *p; p[0] = 3; p[1] = 3; The slice operation on p does the same thing. p is initialized to a null pointer, so you're dereferencing a null pointer. --bb
Jan 19 2007