[Webinar] Streamline your web hosting managementRegister Today

x
?
Solved

How to add this to an array?

Posted on 2003-03-05
11
Medium Priority
?
199 Views
Last Modified: 2010-04-01
How can I add the results of this test to an array? Thanks in Advance.
void CheckValues(int testValues[],int num)
{    
     int j = 0;
     int i = 0;
     for (j = 0; j < num; j++)
     {
          if(testValues[j] < 0)            
             cout<<testValues[j]<<endl;          
        }
     
     for (j = 0; j < num; j++)
     {
           if(testValues[j] >= 0)                        cout<<testValues[j]<<endl;
     }
}

I tried using:
if(testValues[j]>0)
posArray[i++] = testValues[j];

but I get an error about. What's weird is that it worked for another program that I wrote, any ideas ?.

0
Comment
Question by:kamarja
  • 4
  • 3
  • 2
  • +2
11 Comments
 
LVL 22

Expert Comment

by:grg99
ID: 8071653
what's the declaration of posArray like?  What's the error message?  What line is the message about?



0
 
LVL 12

Expert Comment

by:Salte
ID: 8071719
My guess is that you write outside the bounds of the array. The fact that it worked on the other program you wrote was either because you there happened to be within the bounds of the array or because you wrote in some place where the modification had no observable result for your particular case.

When you write to an array you must always keep in mind if the array has room for the new value.

int arr[5];

This array has only room for 5 elements. arr[0], arr[1], arr[2], arr[3] and arr[4].

If you use ANY OTHER value for the index, arr[-1], arr[5], arr[7] the program will most likely not work. You might be lucky and have no observable effect but it definitely won't work the way you intend to anyway. So don't do that.

int * arr = new int[17];

This is also a pointer to an array and just like the previous example the array has exactly 17 elements from 0 to 16. Any index value outside that range will not work the way you intend so don't do that.

You can write beyond the index 16 in this example but not directly, first you have to let the array grow:

int * arr2 = new int[50];
memcpy(arr2,arr,sizeof(int)*17);
memset(arr2 + 17, 0, sizeof(int)*(50-17));

This will allcoate a new array with room for 50 values and copied the old values over. It also made the new elements from 17..49 equal to 0.

delete [] arr; // don't need this array any more.
arr = arr2; // there!

Now arr has room for 50 elements and you can access each of them as an index in the range 0..49.

So, when you add elements to an array, make sure the array has room for the new values. My suspicion is that that is what you didn't do.

Alf
0
 
LVL 1

Expert Comment

by:manirup
ID: 8071765
Hi
Please let me know
1. What is the error message ??
2. In which line does the error occur ??
3. What is the Declaration of PosArray like ???
Bye
Manirup
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 

Author Comment

by:kamarja
ID: 8071945
void CheckValues(int testValues[],int num)
{    
    int j = 0;
    int i = 0;
    posArray[5]; #not really want I want.I want it dynamic.
    negArray[5];
    for (j = 0; j < num; j++)
    {
         if(testValues[j] < 0)
         {
            negArray[i++] = testValues[j];            
            cout<<negArray[i]<<endl;  
         }        
       }
   
    for (j = 0; j < num; j++)
    {
          if(testValues[j] >= 0)  
          {
              posArray[i++] = testValues[j];
              cout<<posArray[i]<<endl;
           }
    }
}

The original program is taking in an arbitrary amount of integers. I set posArray to [5] for testing purposes but It still doesn't work properly I get Garbage values like -858993460. For the negArray".

0
 
LVL 3

Expert Comment

by:cmaryus
ID: 8072153
You need something like this ?

void CheckValues(int *testValues,int num)
{    
   
     int negNumbers = 0;
     int posNumbers = 0;


     int*  posArray = new int[num];
     int*  negArray = new int[num];  // now you have 2 dynamic arrays


     for (int j = 0; j < num; j++)
     {
          if(testValues[j] < 0)
          {
             negArray[negNumbers++] = testValues[j];            
          }
          else
          {
               posArray[posNumbers++] = testValues[j];
          }
     }

     // now you have negNumbers negative numbers and posNumbers positive numbers
     for (int j = 0; j < negNumbers; j++)
     {
          cout << negArray[j] << endl;
     }
     for (int j = 0; j < posNumbers; j++)
     {
          cout << posArray[j] << endl;
     }
     
   // at the end don't forget to destroy the dynamic arrays, if you don't need them..
     delete[] posArray;
     delete[] negArray;
}

or

void CheckValues(int *testValues,int num)
{    
   
     int negNumbers = 0;
     int posNumbers = 0;


     for (int j = 0; j < num; j++)
     {
          if(testValues[j] < 0)
          {
             negNumbers++;            
          }
          else
          {
               posNumbers++;
          }
     }

     int*  posArray = new int[negNumbers];
     int*  negArray = new int[posNumbers];  // now you have allocated exactly the the size you need

     negNumbers = 0;
     posNumbers = 0;

     for (int j = 0; j < num; j++)
     {
          if(testValues[j] < 0)
          {
             negArray[negNumbers++] = testValues[j];            
          }
          else
          {
               posArray[posNumbers++] = testValues[j];
          }
     }

     // now you have negNumbers negative numbers and posNumbers positive numbers
     for (int j = 0; j < negNumbers; j++)
     {
          cout << negArray[j] << endl;
     }
     for (int j = 0; j < posNumbers; j++)
     {
          cout << posArray[j] << endl;
     }
     
   // at the end don't forget to destroy the dynamic arrays, if you don't need them..
     delete[] posArray;
     delete[] negArray;
}
0
 
LVL 3

Accepted Solution

by:
cmaryus earned 200 total points
ID: 8072171
This is more accurate:
void CheckValues(int *testValues,int num)
{    
   
     int negNumbers = 0;
     int posNumbers = 0;


     int*  posArray = new int[num];
     int*  negArray = new int[num];  // now you have 2 dynamic arrays


     for (int j = 0; j < num; j++)
     {
          if(testValues[j] < 0)
          {
             negArray[negNumbers++] = testValues[j];            
          }
          else
          {
               posArray[posNumbers++] = testValues[j];
          }
     }

     // now you have negNumbers negative numbers and posNumbers positive numbers
     for (j = 0; j < negNumbers; j++)
     {
          cout << negArray[j] << endl;
     }
     for (j = 0; j < posNumbers; j++)
     {
          cout << posArray[j] << endl;
     }
     
   // at the end don't forget to destroy the dynamic arrays, if you don't need them..
     delete[] posArray;
     delete[] negArray;
}

or

void CheckValues(int *testValues,int num)
{    
   
     int negNumbers = 0;
     int posNumbers = 0;


     for (int j = 0; j < num; j++)
     {
          if(testValues[j] < 0)
          {
             negNumbers++;            
          }
          else
          {
               posNumbers++;
          }
     }

     int*  posArray = new int[negNumbers];
     int*  negArray = new int[posNumbers];  // now you have allocated exactly the the size you need

     negNumbers = 0;
     posNumbers = 0;

     for (j = 0; j < num; j++)
     {
          if(testValues[j] < 0)
          {
             negArray[negNumbers++] = testValues[j];            
          }
          else
          {
               posArray[posNumbers++] = testValues[j];
          }
     }

     // now you have negNumbers negative numbers and posNumbers positive numbers
     for (j = 0; j < negNumbers; j++)
     {
          cout << negArray[j] << endl;
     }
     for (j = 0; j < posNumbers; j++)
     {
          cout << posArray[j] << endl;
     }
     
   // at the end don't forget to destroy the dynamic arrays, if you don't need them..
     delete[] posArray;
     delete[] negArray;
}
0
 
LVL 12

Expert Comment

by:Salte
ID: 8072383
Hmm... that code doesn't make sense....

Firs you go through the array with testValues and store any negative values in the negarray. Here you make at least one mistake:

negArray[i++] = testValue[j];

This will correctly copy the value to the negArray but it will then advance i so that negArray[i] is NOT the value just copied but is some garbage value that comes after it (and which will be overwritten next time you store a negative value). Thus the cout statement will only output garbage and never output a single valid value.

Secondly after you have done that you have successfully copied i negative values to the negArray. If i <= 5 then this is all well and good, Your cout output garbage but the array itself is valid and has i values in it.

However, then you go through the array again and copies values to posArray. You don't start from 0 but you start from position i. Now, i is the number of negative values in negArray so what that has to do with posArray is beyond me. It doesn't make much sense. Now you could reset i to 0 again and then you would correctly store positive values in posArray. You would again cout garbage for the same reason as before but you would correctly place values into posArray.

Again, assuming that the number of positive values in testArray was less than or equal to 5 this is all well and good and i is now the number of positive values in posArray.

However, you have now lost the count of negative values in negArray. It isn't a big loss, since the value should be equal to num - i so you can manage well without it but it does seem odd that you attempt to store the values in posArray not form 0...number of pos values - 1 but from i..num-1 and this is almost guaranteed to fail unless posArray is as big as num, i.e. num must be no greater than 5 for this to work.

Third you walk through the test array twice, it would probably make more sense to only walk through it once:

int npos = 0;
int nneg = 0;
int negArray[5];
int posArray[5];

for this to work testArray must have no more than 5 negative and no more than 5 positive values and num is therefore also <= 10, probably num <= 5 since even if it is 6 there's a chance that all values are positive or all values are negative and the code will fail.

for (int j = 0; j < num; ++j) {
   if (testValue[j] >= 0) // positive...
      posArray[npos++] = testValue[j];
   else
      negArray[nneg++] = testValue[j];
}

Now, npos and nneg is the number of positive and negative values, npos + nneg == num.

Again, both npos and nneg cannot be more than 5 or the function won't handle it correctly.

If you want to cout the value you need to cout the value you stored. Going back to your code you must do something like:

for (int j = 0; j < num; ++j) {
   if (testValue[j] >= 0) { // positive
      posValue[i] = testValue[j];
      cout << posValue[i++] << endl;
    }
}

This will delay the increment until after you have output the value.

i++ will use the value of i as index but it will increment the variable so that next time you refer to i it will be one greater than it is at this moment.

++i will also increment the value but will do so before it is used, so the value will be one greater than original value of i but will then remain that value so next reference to i will be the same value as the value of ++i.


Alf
0
 

Author Comment

by:kamarja
ID: 8074117
You guys are the best. I am not sure who I should give the points to. I learned a lot from both Salte and cmaryus. Salte, you taught me a lot and cmaryus, you gave me the solutions. However, cmaryus- I got the following error even tho I got the results I was looking for.

Microsoft Visual C++ version 6
debug error!
DAMAGE:after Normal block(#82)
0
 

Author Comment

by:kamarja
ID: 8074315
I added another cout statement and that weird error disappeared. Thank you all for you time. God Bless you. I learned a lot. I will give the points to Cmaryus but Salte- thanks a lot for your comments.
0
 
LVL 3

Expert Comment

by:cmaryus
ID: 8078055
yep, i know why you get error. is in this lines:
>int*  posArray = new int[negNumbers];
>int*  negArray = new int[posNumbers];  // now you have allocated exactly the the size you need

i allocated the pos number array the size of negative numbers and the other way around.it should be:

int*  posArray = new int[posNumbers];
int*  negArray = new int[negNumbers];
0
 

Author Comment

by:kamarja
ID: 8079456
Thanks Dude.
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
Suggested Courses

640 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question