Home > DeveloperSection > Forums > How do I set negative number to index of array in c#.
James Smith

Total Post:48

Points:336
Posted on    April-16-2011 2:27 AM

 C# C# 
Ratings:


 1 Reply(s)
 3495  View(s)
Rate this:

Hi......

I had made a program in c# for shell sorting. When I write this code in c++ then it does not generate any error and sorting is completed but when I run this program in c# then I got an exception that index should not be begative in c++. I want to know that is it possible to make index as negative in c# or I had did any other mistake.
My C# version program is as follows.

static void shellSort(int[] group, int[] h)
{
int step, i, j, x, len, n, k;
n = group.Length;
k = h.Length;
for (step = 0; step < k; step++)
{
len = h[step];
for (i = len; i < n; i++)
{
x = group[i];
j = i - len;
while ((x < group[j]) && (j >= 0)) // <--- Error here "Make sure the index is not a ngative number"
{
group[j + len] = group[j];
j = j - len;
}
group[j + len] = x;
}
}
}

static void Main(string[] args)
{
int[] group, h;
group = new int[8]{6, 7, 15, 8, 18, 25, 4, 0}
h = new int[3] { 5, 3, 1};
shellSort(group,h);

Console.ReadLine();
}

I had taken tis logic from c code which is as follows.

void ShellSort(int a[], int N, int h[], int k)
{
int step,i,j,x,len;
for (step = 0 ; step <k; step ++)
{
len = h[step];
for (i = len; i <N; i++)
{
x = a[i];
j = i-len;
while ((x<a[j])&&(j>=0))
{
a[j+len] = a[j];
j = j - len;
}
a[j+len] = x;
}
}
}

In C, this code have processed successfull. But in C#, i've got a error: "Make sure the index is not a ngative number" at while ((x < group[j]) && (j >= 0)) . But, I didn't repair it.
How could i repair it ?



Awadhendra Tiwari

Total Post:126

Points:882
Posted on    April-16-2011 3:07 AM

In C++, array bounds are not checked and so if you present it with a negative index then it will happily access whatever value corresponds to that memory location even though it's not actually within the array!

Consequently, this line won't give an error even if j is negative:

while ((x<a[j])&&(j>=0))

This doesn't matter here because j has to be non-negative for the while loop to proceed.

However, C# is a safe language and array bounds are always checked (except in unsafe code). The easy fix here is to simply reverse the order of the operands:

while ((j >= 0) && (x < group[j]))

As long as j is non-negative, the second expression isn't evaluated and so it works fine.


Don't want to miss updates? Please click the below button!

Follow MindStick