Murilo :P

C++, Computação, Programação, Web e afins :)

Arrays with negative indexes

with 2 comments

When we to deal with negative ranges in arrays and those ranges can be negative, we do shifts so we can use natural indexes. For example, if we’re given a range from -50 to 20, usually we allocate an array of 70 positions and when indexing an element we shift by +50 so the position -50 is actually stored on the position 0.

These days, while doing random stuff on the internet, I’ve figured that we can easily work with arrays not only starting from zero but starting from any integer we want. To illustrate that, I wrote this function which allocate sz elements of type T where the array’s first element is in min_index position:

template <typename T>
T* alloc(size_t sz, int min_index = 0)
{
	return (new T[sz]) - min_index;
}

An example of use:

int main()
{	
	char* p = alloc<char>(70, -50);
	
	p[-50] = 'h'; p[-49] = 'e'; 
	p[-48] = 'l'; p[-47] = 'l';
	p[-46] = 'o'; p[-45] = '\0';
	
	std::cout << &p[-50] << '\n';
	
	for (int i = -50; i < -45; ++i) {
		std::cout << p[i] << '\n';
	}
}

The result, as expected:

hello
h
e
l
l
o
About these ads

Written by Murilo Adriano

29 de October de 2012 at 14:24

Posted in C/C++, Programação

Tagged with , ,

2 Responses

Subscribe to comments with RSS.

  1. (new T[sz]) – min_index;

    Aren’t you writing on the memory outside the allocated block?

    Felipe Carvalho

    30 de October de 2012 at 02:19

    • No Felipe, given my example, lets say that ‘p = new T[sz]‘ returns a pointer to position 1000 (in decimal). So, if ‘sz == 70′, the range allocated is 1000 to 1069.

      Now, if ‘min_index == -50′, ‘p – min_index’ would be equal to 1050. So, let ‘ptr = p – min_index’ when you access the position ‘ptr[-50]‘ you would actually be accessing the position ‘p – (-50) – 50′ which is ‘p’ and the upper bound is ‘ptr[19]‘ which is ‘p – (-50) + 19′ which is equal to 1069.

      Murilo Adriano

      30 de October de 2012 at 08:47


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 582 other followers

%d bloggers like this: