473,796 Members | 2,661 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Negative indices to a vector: Valid?


Hello,

I have the following code:

#define N 99
double *ptr;
double *storage;
int index;

storage = calloc(N , sizeof(double)) ;
ptr = &storage[N/2];
...
...
...
free(storage);
Now ptr points into the middle of the allocated memory area, and I can
access elements in the array as ptr[index], where index is a *signed*
variable which can take the values -N/2,...N/2. Is this legal
behaviour? Or should the index operator only be given unsigned
arguments?

I have tried using a couple of different compilers on Linux and IRIX,
and it seems to work, but it does give me a slightly queasy feeling.
Regards

Joakim

--
Joakim Hove
hove AT ntnu.no /
Tlf: +47 (55 5)8 27 13 / Stabburveien 18
Fax: +47 (55 5)8 94 40 / N-5231 Paradis
http://www.ift.uib.no/~hove/ / 55 91 28 18 / 92 68 57 04
Dec 22 '05 #1
8 5171
This is perfectly legal. The array index is treated as a signed integer
in C.

a[i] is a shorthand way of writing
a + sizeof(a)*i

Thus if i is negative, the final entry addressed would be before a[0].

--
EventStudio System Designer 2.5 - http://www.EventHelix.com/EventStudio
Sequence Diagram Based Real-time and Embedded System Design Tool

Dec 22 '05 #2
Joakim Hove wrote:
Hello,

I have the following code:

#define N 99
double *ptr;
double *storage;
int index;

storage = calloc(N , sizeof(double)) ;
All bits 0 (which is what calloc provides) is *not* guaranteed to
represent a floating point 0, it could even be a trap representation.
Also, using "sizeof *storage" would be better than "sizeof(double) "
because if the type ever changes (say, to long double) then you will
still get the correct amount of space.
ptr = &storage[N/2];
...
...
...
free(storage);
Now ptr points into the middle of the allocated memory area, and I can
access elements in the array as ptr[index], where index is a *signed*
variable which can take the values -N/2,...N/2. Is this legal
behaviour? Or should the index operator only be given unsigned
arguments?
What you are doing is completely legal. You could even do it if you were
using an array. Obviously, you have to be careful to ensure you don't go
off the end of the allocated space which can require a little more thought.
I have tried using a couple of different compilers on Linux and IRIX,
and it seems to work, but it does give me a slightly queasy feeling.


You are right to ask rather than relying on experimental results, since
there are "illegal" things that will "work" on some platforms but fail
on others, one of the classic (IMHO) examples of this being modifying
string literals.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Dec 22 '05 #3
Joakim Hove wrote:

Hello,

I have the following code:

#define N 99
double *ptr;
double *storage;
int index;

storage = calloc(N , sizeof(double)) ;
ptr = &storage[N/2];
...
...
...
free(storage);

Now ptr points into the middle of the allocated memory area, and I can
access elements in the array as ptr[index], where index is a *signed*
variable which can take the values -N/2,...N/2. Is this legal
behaviour?


Only if by "Now", you mean before:

free(storage);

--
pete
Dec 22 '05 #4
Joakim Hove wrote:
Hello,

I have the following code:

#define N 99
double *ptr;
double *storage;
int index;

storage = calloc(N , sizeof(double)) ;
ptr = &storage[N/2];
...
...
...
free(storage);
Now ptr points into the middle of the allocated memory area, and I can
access elements in the array as ptr[index], where index is a *signed*
variable which can take the values -N/2,...N/2. Is this legal
behaviour? Or should the index operator only be given unsigned
arguments?


Legal, provided N is odd (as shown).

However, do not be fooled into thinking that "just any"
offset will work. The above is all right because `ptr' does
in fact point into the allocated area. The language guarantees
that `ptr = &storage[k]' will work for all k between 0 and N
(inclusive at both ends), but not for k outside that range.
You may occasionally encounter `ptr = &storage[-1]' as part of
an attempt to imitate the 1-based arrays of Fortran, say, but
such code is incorrect and need not work at all.

--
Eric Sosman
es*****@acm-dot-org.invalid
Dec 22 '05 #5
>This is perfectly legal. The array index is treated as a signed integer
in C.

a[i] is a shorthand way of writing
a + sizeof(a)*i


No, a[i] is a shorthand way of writing *(a + i). It's also equivalent
to i[a].

It may also be considered as a shorthand way of writing
*(a addl (sizeof(a) * i)), where addl is an assembly-language
addition operator.

It is allowed for i to be negative provided the storage referred
to exists.

Gordon L. Burditt
Dec 22 '05 #6
Gordon Burditt wrote:
This is perfectly legal. The array index is treated as a signed integer
in C.

a[i] is a shorthand way of writing
a + sizeof(a)*i
No, a[i] is a shorthand way of writing *(a + i). It's also equivalent
to i[a].


Yes.
It may also be considered as a shorthand way of writing
*(a addl (sizeof(a) * i)), where addl is an assembly-language
addition operator.


I think it should be sizeof(*a), instead of sizeof a.

--
pete
Dec 22 '05 #7

Thanks to all of you who answered. It makes my code look much nicer,
so I am grateful that I can rely on this approach.
Joakim

--
Joakim Hove
hove AT ntnu.no /
Tlf: +47 (55 5)8 27 13 / Stabburveien 18
Fax: +47 (55 5)8 94 40 / N-5231 Paradis
http://www.ift.uib.no/~hove/ / 55 91 28 18 / 92 68 57 04
Dec 22 '05 #8
> No, a[i] is a shorthand way of writing *(a + i). It's also equivalent
to i[a].


Agreed. Pointer arithmatic internally multiples to take care of the
sizeof.

--
EventStudio System Designer 2.5 - http://www.EventHelix.com/EventStudio
Sequence Diagram Based System Design and Object Modeling Tool

Dec 24 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
2155
by: dan | last post by:
I was recently surprised, and quite shocked in fact, to find that Python treats negative indices into sequence types as if they were mod(length-of-sequence), at least up to -len(seq). This fact is *deeply* buried in the docs, and is not at all intuitive. One of the big advantages of a high-level language such as Python is the ability to provide run-time bounds checking on array-type constructs. To achieve this I will now have to...
19
2609
by: David Abrahams | last post by:
Can anyone explain the logic behind the behavior of list slicing with negative strides? For example: >>> print range(10) I found this result very surprising, and would just like to see the rules written down somewhere. Thanks,
5
2905
by: Ross MacGregor | last post by:
I have a very simple yet complicated problem. I want to generate a random list of indices (int's) for a container. Let's say I have a container with 10 items and I want a list of 3 random indices for that container. So I need to generate 3 unique numbers from integer range . There seems to be no simple and efficient way to do this. Any implementation I have come up with involves maintaining a list of
11
8882
by: Steve | last post by:
Hi, I'm using a std::vector to store a list of user defined objects. The vector may have well over 1000 elements, and I'm suffering a performance hit. If I use push_back I get a much worse perfomance than if I first define the vector of a given size, then write to the elements with myvec = However, I'm currently thinking that it isn't feasible to obtain the vector size, so really need to resize the vector dynamically as I go. Is...
4
1509
by: slurper | last post by:
tx for answer Bazarov i have another problem i have a vector with 20 elements in it (20 ints). i'd like to have the elements sorted in ascending order, but somehow i need to know what index the element was at in the original vector. someone?
1
4826
by: illegal.prime | last post by:
So I see from the documentation here: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemCollectionsArrayListClassBinarySearchTopic.asp That the code uses the less than operator: int myIndex=myList.BinarySearch( myObject ); if ( myIndex < 0 ) when using the BinarySearch method and in my own experience I see that sometimes it returns other negative values (other than -1).
11
3737
by: drtimhill | last post by:
I'm just starting out on Python, and am stumped by what appears an oddity in the way negative indices are handled. For example, to get the last character in a string, I can enter "x". To get the 2nd and 3rd to last, I can enter x etc. This is fine. Logically, I should be able to enter x to get the last and next to last characters. However, since Python doesn't distinguish between positive and negative zero, this doesn't work. Instead, I...
2
7254
by: smichr | last post by:
It seems to me that the indices() method for slices is could be improved. Right now it gives back concrete indices for a range of length n. That is, it does not return any None values. Using an example from clpy about this the indices for a 'None, None, -2' slice for a range of length 10 are given as '9, -1, -2'. The problem is that these concrete values cannot be fed back into a slice so that a slice will extract the same elements that...
2
3893
by: ajcppmod | last post by:
I'm really confused about results of slices with negative strides. For example I would have then thought of the contents of mystr as: indices 0 1 2 3 4 5 6 7 8 content m y s t r i n g with mystr = 'my '
0
9684
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10236
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10182
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10017
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7552
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6793
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4120
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3734
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2928
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.