COMPGROUPS.NET | Search | Post Question | Groups | Stream | About | Register

### what does [-1] mean?

• Email
• Follow

```is this valid? what does it mean?

char *abc = "hello";
abc++;

char d = abc[-1];

does it work?

thanks
Todd.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated.    First time posters: Do this! ]
```
 0

See related articles to this posting

```d will have a value of 'h'. Square brackets basically do the same as
pointer arithmetic, ie:

abc[-1] is equivalent to *(abc - 1)

toddmarshall2002@yahoo.com wrote:
> is this valid? what does it mean?
>
> char *abc = "hello";
> abc++;
>
> char d = abc[-1];
>
> does it work?
>
> thanks
> Todd.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated.    First time posters: Do this! ]

```
 0

```toddmarshall2002@yahoo.com wrote:
> is this valid? what does it mean?

Yes it is.
>
> char *abc = "hello";

This creates a pointer to char, it creates an six element
array of const char in some unspecified static location with
the value "hello" (including a null terminator) in it.   It
uses a deprecated conversion to char* to initialize the pointer.

> abc++;

Adds one to the pointer, *abc now is 'e'

>
> char d = abc[-1];

abc[-1] is defined to be the same as *(abc + -1)
The value is 'h'.   (abc + -1) is the original
beginning of the array.

Note that when doing math on pointers, once you
move the pointer value outside of the array it
originally pointed to (with the exception of one
past the end), you have undefined behavior.

That doesn't happen here, but the opposite:
char* abc = "hello";
abc--;
char d = abc[1]
is undefined behavior.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated.    First time posters: Do this! ]

```
 0

```<toddmarshall2002@yahoo.com> schrieb im Newsbeitrag
> is this valid? what does it mean?
>
> char *abc = "hello";
> abc++;
>
> char d = abc[-1];
>
> does it work?

For built-in types a[b] is equivalent to *(a + b). So abc[-1] is valid
as long as abc points at least one item after the start of some array.
You can even write (-1)[abc].

HTH
Heinz

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated.    First time posters: Do this! ]
```
 0

```toddmarshall2002@yahoo.com wrote:
> is this valid? what does it mean?

Yes, it does work, and will set d to the character 'h'.  Remember that
for pointers, a[b] refers to the value at an offset b from where a is
pointing.[1]

> char *abc = "hello";

This sets abc to point to the first character in the character array
"hello", the 'h'.

> abc++;

This makes abc point to the next element in the array it is pointing to.
So now abc is pointing to the 'e'.

> char d = abc[-1];

This says "get the character 1 before wherever abc is pointing.  This is
the 'h' at the start of the string.

[1] Technically on pointers a[b] is equivalent to *(a + b), which is
equivalent to *(b + a) which is equivalent to b[a].  Common style
dictates that the pointer should be outside the subscript, making the
statement true as long as you follow that style.

-- MJF

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated.    First time posters: Do this! ]
```
 0

```On 20 Oct 2004 12:21:01 -0400, toddmarshall2002@yahoo.com wrote:

> is this valid? what does it mean?
>
> char *abc = "hello";
> abc++;
>
> char d = abc[-1];
>
> does it work?
>
> thanks
> Todd.

abc should be declared as char const *, otherwise the code looks valid
to me.

The C++ standard (see 8.3.4.6) seems to allow the syntax "abc[-1]"
since abc[n], where n is an integer, is equivalent to *(abc + n).
Since the above code pre-increments the pointer abc by one, the
character variable d should contain 'h' after your code snippet runs.

Whether or not this is good coding practice, however, is another
story.

--
Bob Hairgrove

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated.    First time posters: Do this! ]
```
 0

```<toddmarshall2002@yahoo.com> wrote in message

> is this valid? what does it mean?
> char *abc = "hello";
> abc++;
> char d = abc[-1];

a[b] is just syntax sugar for *(a+b).
so abc[-1] or (-1)[abc]  both mean *(abc-1), what will yield 'h' in the
example.

> does it work?

Sure, as long as pointer math is legal, iow as long as the result is
still
within the array.

Paul

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated.    First time posters: Do this! ]

```
 0

```toddmarshall2002 wrote:

> is this valid? what does it mean?
>
> char *abc = "hello";

That should be char const *

> abc++;
>
> char d = abc[-1];

It means this passes:

assert('h' == d);

> does it work?

Yep. A pointer is valid if it points into an array (or off the end of an
array by one). Dereferencing a pointer is valid if it points at a valid
object.

An array subscript is the same as pointer arithmetic followed by
dereferencing. These are the same:

abc[1];
*(abc + 1);

So, put them all together, and *(abc - 1) is well-formed and well-defined,
so abc[-1] is too.

--
Phlip
http://industrialxp.org/community/bin/view/Main/TestFirstUserInterfaces

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated.    First time posters: Do this! ]

```
 0

```toddmarshall2002@yahoo.com wrote:
> is this valid? what does it mean?
>
> char *abc = "hello";
> abc++;
>
> char d = abc[-1];
>
> does it work?

Yes, it will work. abc effectively a pointer, and abc[0] is the contents
of the memory at the location pointed to at abc, in this case the
charachter 'h'. abc++ will increment the pointer by one which (assuming,
and it's an assumption of unknown size...., but assuming that your
implementation stores arrays as contiguous blocks of memory) should then
point abc the next item in the array. Therefore abc[0] is 'e', abc[-1]
might, if you're lucky, point to 'h'.

Note all the occurrences of 'might', 'should', and 'if' in the above
paragraph. If you really need to use this idiom, make sure you know
everything there is to now about the compiler you're using, and every
other compiler that anyone might possibly use in the future to compile
this code.

Tiff
--

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated.    First time posters: Do this! ]
```
 0

```On 20 Oct 2004 12:21:01 -0400, toddmarshall2002@yahoo.com wrote:

>is this valid? what does it mean?
>
>char *abc = "hello";
>abc++;
>
>char d = abc[-1];

It's valid, but using this feature of C++ should be avoided.  It's
generally better to create a secondary pointer to traverse the string and
keep the original pointer when you have to start from the beginning.

The [-1] in the array access the element one step before the current
position of the pointer.  In this case, *abc points to the second element
to produce the string "ello" (it advanced by one letter).  Accessing the
element before the pointer would provide the letter 'h'.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated.    First time posters: Do this! ]
```
 0

```Todd asked:

> is this valid? what does it mean?
>
> char *abc = "hello";
> abc++;
>
> char d = abc[-1];
>
> does it work?

The last line is identical in meaning to:

char d = *(abc - 1);

which sets d to the character 'h'. If this seems weird, just think of how it
works with a positive index - eg. abc[3] == *(abc + 3)

BTW, char *abc should really be const char *abc - as far as I know, the fact
that a literal string like "hello" can be assigned to a char* is for
compatibility with C.

David Fisher
Sydney, Australia

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated.    First time posters: Do this! ]
```
 0

```<toddmarshall2002@yahoo.com> wrote in message
> is this valid? what does it mean?
>
> char *abc = "hello";
> abc++;
>
> char d = abc[-1];
>

According to C++ standard (paragraph 8.3.4 (6)),
x[y] is equivalent to *(x+y), except when operator[]
is invoked for a class.

Thus, abc[-1] should mean the same as *(abc-1) - the item
that is just before the one to which abc points.

> does it work?

I think with standard conforming compiler it should.
However, this is probably one of those "don't try this at home" things.

Only actual experiment can verify whether it works with *your* compiler.

Ivan

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated.    First time posters: Do this! ]
```
 0

```On 20 Oct 2004 12:21:01 -0400, toddmarshall2002@yahoo.com wrote in
comp.lang.c++.moderated:

> is this valid? what does it mean?
>
> char *abc = "hello";

This defines an unnamed array of 6 constant characters, 'h', 'e', 'l',
'l', 'o', '\0'.  It also defines a pointer to non-constant char,
'abc', and sets it to point to the first character, the 'h',  of the
unnamed array of constant characters.  C++ makes an exception in its
typing system to allow the address of a string literal to be assigned
to a pointer to non-constant char, for backwards compatibility with C
code.

> abc++;

This advances the pointer by one byte, so it now points to the second
character, the 'e', in the string literal.

> char d = abc[-1];

This reads the value of the character before the 'e' that abc points
to, the 'h'.

> does it work?

It works and it is perfectly legal to use a negative index from a
pointer into an array, as long as the result does not go past the
beginning of the array.

So abc[-2] would produce undefined behavior.

> thanks
> Todd.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~ajo/docs/FAQ-acllc.html

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated.    First time posters: Do this! ]
```
 0

```toddmarshall2002@yahoo.com wrote:
> is this valid? what does it mean?
>
> char *abc = "hello";
> abc++;
>
> char d = abc[-1];
>
> does it work?

abc[-1] generates a reference to the character before 'h' in "hello".
whether it "works" or not depends on your definition of "works".
It's undefined behavio.
--
A. Kanawati
NO.antounk.SPAM@comcast.net

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated.    First time posters: Do this! ]

```
 0

```toddmarshall2002@yahoo.com wrote in message news:<c7aadd5c.0410190529.72bf716c@posting.google.com>...
> is this valid? what does it mean?
>
> char *abc = "hello";
> abc++;
>
> char d = abc[-1];
>
> does it work?
>

It's valid, and it works. It returns 'h'.

abc[-1] is equivalent to *(abc-1)
So, if abc points in the middle of a string (and not at the beginning
of it), it's perfectly valid.

Best,
John

John Torjo,    Contributing editor, C/C++ Users Journal
-- "Win32 GUI Generics" -- generics & GUI do mix, after all
-- http://www.torjo.com/win32gui/
+ bitmap buttons, tab dialogs, hyper links, lite html

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated.    First time posters: Do this! ]
```
 0

```"Antoun Kanawati" <NO.antounk.SPAM@comcast.net> wrote in message
news:nVJdd.432324\$Fg5.157704@attbi_s53...
> toddmarshall2002@yahoo.com wrote:
> > is this valid? what does it mean?
> >
> > char *abc = "hello";
> > abc++;
> >
> > char d = abc[-1];
> >
> > does it work?
>
> abc[-1] generates a reference to the character before 'h' in "hello".
> whether it "works" or not depends on your definition of "works".
> It's undefined behavio.
>

Why do you think it's undefined?
I believe it is pretty much defined by the standard (paragraph 8.3.4 (6)).

Ivan

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated.    First time posters: Do this! ]
```
 0

```Ivan Krivyakov wrote:
>>toddmarshall2002@yahoo.com wrote:
>>>is this valid? what does it mean?
>>>
>>>char *abc = "hello";
>>>abc++;
>>>
>>>char d = abc[-1];
>>>
>>>does it work?
>>
>>abc[-1] generates a reference to the character before 'h' in "hello".
>>whether it "works" or not depends on your definition of "works".
>>It's undefined behavior.
>>
> Why do you think it's undefined?
> I believe it is pretty much defined by the standard (paragraph 8.3.4 (6)).

Oooooops.  I missed the abc++ line.

Yes, in this case, this is quite well defined.  I was seeing:

char *abc = "hello";  // no abc++;
char d = abc[-1];

When you consider the 'abc++' statement, abc[-1] refers to the 'h' in
"hello".

My apologies.

This may be a good time to consider normal sleeping hours :)
--
A. Kanawati
NO.antounk.SPAM@comcast.net

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated.    First time posters: Do this! ]
```
 0

16 Replies
103 Views

Similar Articles

12/12/2013 2:16:56 PM
[PageSpeed]

Similar Artilces:

Generate a Random number between -1 and 1 with mean 0
Hi, I need help generating a random number between -1 and 1 with a specified mean and variance. I'm using c=a + b*randn() with 'a' as the mean and b as the standard deviation but the problem is that since the randn function only generates a mean zero standard deviation 1 random variable then I might end up having c greater or less than 1. Thanks "Natialol" wrote in message <j55j7k\$aj0\$1@newscl01ah.mathworks.com>... > Hi, > > I need help generating a random number between -1 and 1 with a specified mean and variance. > > I'm using c=a + b*ra...

what does 2>&1 mean?
in this example: usage() { echo "Usage: letter-count.sh file letters" 2>&1 # For example: ./letter-count2.sh filename.txt a b c exit \$E_PARAMERR # Not enough arguments passed to script. } Thanls It means you didn't bother to read even a tiny bit before you posted your question. puzzlecracker wrote: > in this example: > usage() > { > echo "Usage: letter-count.sh file letters" 2>&1 > # For example: ./letter-count2.sh filename.txt a b c > exit \$E_PARAMERR # Not enough arguments passed to script. > } &g...

what dose this float value mean ( -1.#IND0 )
what dose this float value mean？ The value is: -1.#IND0 Car wrote: > what dose this float value mean？ > > The value is: > > -1.#IND0 That doesn't look much like C to me. More context would be helpful - where did you see it? Can you show us a snippet of code with this in? In article <b873bae0-2e32-4ced-a82d-5399f7abc0c9@62g2000hsn.googlegroups.com>, Car <B1FABECE@gmail.com> wrote: >what dose this float value mean？ > >The value is: > >-1.#IND0 It's probably what your system prints for some kind of NaN ("not a ...

Meaning of name : in std_logic_vector(num_rams(g_resize_num)
In a project I saw the following code: name : in std_logic_vector(num_rams(g_resize_num) - 1 downto 0); with g_resize_num = 1. Now I wanna now what the meaning is of num_rams(g_resize_num). Is this some kind of constant in a constant or what is the meaning of this? I searched already on the web, but I didn't found anything because I also don't now what to search for. Hope someone can help me. On 29 Jul, 08:14, Pieter <pieter.huy...@gmail.com> wrote: > In a project I saw the following code: > name =A0 =A0: in std_logic_vector(num_rams(g_resize_num) - 1 downto 0); w= ith >...

Test vote 2005: 1.0 shall mean fp-number ONE, not double-number TEN
Just for fun (and perhaps useful for Forth-200x): Extracts from the current standard docs say: 8.3.2 Text interpreter input number conversion When the text interpreter processes a number that is immediately followed by a decimal point and is not found as a definition name, the text interpreter shall convert it to a double-cell number. A.12.3.7 Text interpreter input number conversion The Technical Committee has more than once received the suggestion that the text interpreter in Standard Forth systems should treat numbers that have an embedded decimal point, but no exponent, as floating-poi...

Re: What's the meaning of : array _length {&nvarsc} 8 _temporary_ (&nvarsc*1);
A temporary, numeric array is being defined with &nvarsc elements. The parenthesis is initializing each bucket of the numeric _length array to the value of 1. It's "multiplying" the initial value of 1 by the number of buckets. The variables underlying temporary arrays are automatically dropped. When defining the dimension of an array, SAS will accept (), {} or []. However, the initial values thingy only accepts (). -----Original Message----- From: SAS(r) Discussion [mailto:SAS-L@LISTSERV.UGA.EDU]On Behalf Of toby dunn Sent: Wednesday, January 12, 2005 4:51 PM To: SAS-L@...

1 - 1, 1 -1, 1-1, 1
Hi, I have a question regarding lexical analysis. I recently came across a bug in our lexical analyser in phc (www.phpcompiler.org), that I am unsure how to solve. This is the problem: our current definition for integer constant looks something like INT ([1-9][0-9]*)|0 In particular, note that it does not allow for an (optional) "+" or "-" at the start of the integer. This means that the strings "1 - 1", "1 -1" and "1-1" all generate the same sequence of three tokens INT(1), OP(-), INT(1), for which the syntax analyser generates the subtr...

focus issues going from 1.3.1 to 1.4.1?
I have a program where I'm using JFrames that pop up JDialogs that aren't modal. I wasn't having this issue when I was in 1.3.1, but now that I'm in 1.4.1 the JDialogs are appearing behind the main JFrame when they pop up and when I select them to the front they'll go back behind again after like the first 10 seconds. But once I select it to the front again it doesn't do it anymore. It's really weird. Has anyone ever seen this before? On Tue, 01 Jul 2003 14:58:54 GMT, "Stephen Hoskins" <shoskins@tridsys.com> wrote or quoted : > But once I ...

(??] [1/2]
begin 644 TEST.txt M2&5L;&\@=&AI<R!I<R!A('1E<W0@9FEL92!F;W(@;7D@;F5W('!R;V=R86TN \$+BXN+@`` ` end Posted Via Usenet.com Premium Usenet Newsgroup Services ---------------------------------------------------------- ** SPEED ** RETENTION ** COMPLETION ** ANONYMITY ** ---------------------------------------------------------- http://www.usenet.com ...

Integrating (1+Sin[1/x]) from .1 to 1 in Radians Speed Test
Calculated processor speeds for the 48gx, 33sii, 42s, 50g, and ti-89, all times calibrated relative to the 4mhz speed indication given by the 48gx self test, match means answer verified to the 12th digit: integral(1+Sin[1/x]) ..01-1-48gx.-3min15sec-match-4mhz ..01-1-32s2-14min-4sec-match-925khz ..01-1-42s-11min-30sec-match-1.1mhz ..01-1-ti89-2min-09sec-match-6mhz ..01-1-50g-2min-09sec-match-6mhz FYI Ben wrote: > Calculated processor speeds for the 48gx, 33sii, 42s, 50g, and ti-89, > all times calibrated relative to the 4mhz speed indication given by the > 48gx self test, match mea...

[ANN] unicorn 1.0.1 and 1.1.2
Changes: Theses release fix a long-standing bug where the original PID file is not restored when rolling back from a USR2 upgrade. Presumably most upgrades aren't rolled back, so it took over a year to notice this issue. Thanks to Lawrence Pit for discovering and reporting this issue. About Unicorn: Unicorn is an HTTP server for Rack applications designed to only serve fast clients on low-latency, high-bandwidth connections and take advantage of features in Unix/Unix-like kernels. Slow clients should only be served by placing a reverse proxy capable of fully buffering bo...

CSMenu is a small freeware application designed to replace the default start menu that comes with Windows 7. The classic start menu, still the favorite of many computer users, is completely lacking from Windows 7. Without downloading third party software such as this, there is no way to return it as there was in Windows Vista. Many people prefer the classic start menu for a number of reasons. It is generally easier to find programs, especially those which you do not use so often. You can download CSMenu immediately and without having to pay anything. It is easy to install, and if yo...

AVS Image Converter 1.1.1.31
Convert your pictures, improve their quality and look, apply various effects, copyright converted images. It is easy and fast with AVS Image Converter. Convert tons of images to all key formats at one go! Easily work with such formats as JPEG, RAW, GIF, etc. Apply auto-correction settings to improve image parameters such as brightness and contrast. Choose various effects - make your pictures look like black-and-white pics, or old faded photographs. Resize pictures and prepare them for future slideshows or fit them to popular printing formats. Select a logo and apply it to converted pi...

AVS Photo Editor 1.1.1.53
Edit your pictures and improve their look with AVS Photo Editor. Crop, resize, rotate, zoom pictures. Adjust color parameters such as balance, brightness, contrast and saturation. Remove minor defects - red-eye effect, tiny imperfections. Reduce image noises and use the Deblur tool feature to sharpen or soften object shapes. Select among sets of pre-made effects to make your pictures look like old faded photographs or create stylish monochrome black-and- white pictures. Easily work with various image formats such as JPEG, BMP, TIFF, PNG, GIF, etc. AVS Photo Editor is a part of the A...

I have gone to CPAN and found that the author(s) have not been keeping up-to-date versions of the NetSNMP and SNMP modules with this repository. I have gone to Google with no luck locating the latest/greatest versions of either of these modules. Does any one know of a stable and reputable ftp-mirror site for these modules? Thanks in advance, Joe Cipale * joe.cipale@radisys.com schrieb: > I have gone to CPAN and found that the author(s) have not been keeping > up-to-date versions of the NetSNMP and SNMP modules with this > repository. > > I have gone to Google with no luck...

for i in {1..\$1}, \$1 can't be used
Shell script interpreters are unable to recognize variable in a for loop control but I don't want to hard code the iteration end in the for loop every time, what can be done to make the script flexible? On Tue, 28 Sep 2010 08:16:50 -0700, ela wrote: > Shell script interpreters are unable to recognize variable in a for loop Hmmm, maybe you might want to spend some time looking through http://www.tldp.org/LDP/abs/html/loops1.html "ela" <ela@yantai.org> wrote in news:i7rc54\$qsr\$1 @ijustice.itsc.cuhk.edu.hk: > Shell script interpreters are una...

1.9.1?
Hi there, I'm about 2 weeks into my learning attempt at Ruby (1.8.6 is what I've cut my teeth on). Can someone give me a rational assessment of the differences between the two language versions, and which one I should continue to pursue? I'm mainly using Ruby with Rails to make basic webapps for my own edification. Thanks! Alex On Tue, Feb 3, 2009 at 6:14 PM, yuckysocks <alex.m.mcpherson@gmail.com> wro= te: > Hi there, > > I'm about 2 weeks into my learning attempt at Ruby (1.8.6 is what I've > cut my teeth on). > > Can someone give me a ration...

opengl version 1.1 or 1.5.3??
I'm having some problems implementing a skybox. Before I can ask about that, I need to figure out what is going wrong with my OpenGL installation. I'm trying to use an OpenGL feature present in version 1.2 and later ( GL_CLAMP_TO_EDGE - trying to get rid of skybox texture seams ). I'm getting compile errors which leads me to believe I have problems with my OpenGL installation since the following C statement, version=glGetString(GL_VERSION); returns the string "1.5.3" but a global search of all GL.h include files only brings up include files for version 1.1 . ...