December 20, 2003 Re: twinkle twinkle little stars | ||||
---|---|---|---|---|
| ||||
On Sat, 20 Dec 2003 10:42:46 +0000, Adam Harper <a-news-d@harper.nu> wrote: > On Sat, 20 Dec 2003 04:19:24 -0500, Lewis wrote: > > One of the most confusing things for me in D or any C style language (curly braces and such) is the use of stars * here and there and what there placement means... > > "*"'s are the pointer declaration/dereference character in C, C++ and D. They are also the multiplication operator. The placement decides whether they are being used as one or the other. Generally, the "*" means multiply when it doesn't: > > - Follow a type (e.g. "int *", "char *", etc.) > - Come before a pointer variable > > Whitespace doesn't really matter. > > To give you a code example: > > > int i = 1; > > int i2 = 2; > > int* i_ptr = &i; // "i_ptr" is a pointer to "i" > > > > i = i * i2; // i = i (multiplied by) i2 > > i2 = * i_ptr; // i2 = (The value pointed to by i_ptr) > > To declare a pointer you place a "*" before the variable name, any of the following are valid pointer declarations: > > > int* i; > > int * i; > > int *i; > > To make the pointer actually point to something you need to assign it a reference, this is done by placing the "&" character before a variable name: > > > int i = 123; > > int* ptr = &i; // "ptr" points to "i" > > To access the value pointed to by a pointer you need to dereference it, this is done by placing a "*" before the pointers name: > > > printf( "%d", ptr ); // Will print the memory address that > > // "ptr" points to, e.g. "-1073743116" > > printf( "%d", *ptr ); // Will print "123" > > > > for example i know that *MyString would indicate a pointer to MyString if my guess is correct. > > "*MyString" is a pointer /called/ "MyString", not a pointer /to/ "MyString". Pointers are just variables like everything else and they share the same namespace(?), so you can't have: > > > int MyInt; > > int *MyInt; > > It's easier if you use the D type declaration [http://www.digitalmars.com/d/declaration.html] (which is also valid in C), where the "*" comes after the type instead of before the variable name: > > > int* MyInt; > But 'int* x,y" is valid in both C and D but means entirely different things! D continually surprises me > <<snip>> Karl Bochert |
Copyright © 1999-2021 by the D Language Foundation