i have a prb here, i have been asked to make a procedure which recieve an array of integers,its lenght, and two integers X and Y as parameters. now the procedure needs to find X in the array and put Y ahead of it ( Y is not in the array) the prb is that i dont know how to put an element inside an array while its dimension is already fixed! is there need of declaring the array dynamic? plz help.

thanks in advance

Recommended Answers

All 13 Replies

Generally when working with arrays like this, you should be taking two size parameters: one for the number of filled slots, and one for the capacity. That way if the array is full you can throw a proper error. So option #1 is to change the way your function is called and do this:

void update ( int a, int size, int len, int x, int y )
{
  if ( len >= size )
    return;

  //...
}

Option #2 is to expect a dynamically allocated array so you can resize it, but a bunch of new problems can come up with this, like invalidating every pointer the caller has into the array and of course, requiring that the caller give you a dynamic array.

Option #3 is my preference, and that option is to ditch the array and use a std::vector object.

There are other options, but the get progressively more and more distasteful. ;)

You meant to say:

void update ( int a*, int size, int len, int x, int y )
//or
void update ( int a[], int size, int len, int x, int y )

right?

commented: With *a, it is :) +21

>right?
Right. Well, the second one as the first is a syntax error. ;)

correct me if im wrong bt from ur first option i assume that u are stating a condition where if the array reaches its limit it will give u an error message?
now to clarify my question
since i have to put Y( an integer not included in array) before X (another integer which is in the array )i have to move every element including X ,after Y,one place to the right. now the prb is that if i have n(dimension of the array) how can i put the last element in n+1?

>ur first option i assume that u are stating a condition where
>if the array reaches its limit it will give u an error message?
Something to that effect, yes.

>now the prb is that if i have n(dimension of the array)
>how can i put the last element in n+1?
That's a problem if the array is full. By full I mean that when items are added, they're added in such a way that there are no holes between two items; all of the "unused" slots are contiguous and at the end. In that case, you can certainly shift and add as long as the number of items currently in the array is less than n.

Another situation is where there are holes in the array and the holes are initialized to some default value. In that case, you can only shift and add without losing values if the last value ( array[capacity-1] ) is a default value. But in that case you might not always needs to shift if the slot before X is a default value, then you can simply overwrite it with Y and be done.

well ofcourse the array is full since u have to first enter the array,then enter X and Y and after that calling the procedure, telling it to put Y before X and shift all the others including X.So whats ur opinion now that the array is full?
i wrote something like this, without the Main function obviously...

oid proc( int vett[],int n, int x, int y){
     
     int i;
   for(i=0;i<n;i++)
   if(vett[i]==x){
                 int j;
                 for(j=n+1;j<=i;j--){
                 vett[j]=vett[j-1];
                 vett[i]=y;
                 
                 for(j=0;j<n;i++)
                     cout << vett[j];}                
                 
                  }}

>well ofcourse the array is full since u have to first enter the array
Of course. :icon_rolleyes: I see you completely failed to see the multiple equally viable ways an array could be passed to your function, but thanks for clarifying your actual requirement.

>So whats ur opinion now that the array is full?
You're SOL. Sorry. Either you lose data by shifting it away, or you preserve data by failing in all cases.

Damn i didnt expect it to be that easy LOL!!
simply declared another array in the procedure with n+1(one dimension more than the array recieved) and copied elements of the array into it! here is the code:

#include <cstdlib>
#include <iostream>

using namespace std;


void proc( int vett[],int n, int x, int y){
     
     int a[n+1];
     int i,j=0;
     
     for(i=0;i<n;i++){
     if(vett[i]!=x){
                   a[j]=vett[i];
                     j++;
                   }
                
     else{        
           a[j]=y;
           a[j+1]=x;
           j+=2;
        }           }                  
                 
        

for(j=0;j<n+1;j++)
 cout << a[j];      
}
     
int main(int argc, char *argv[])
{
    
    const int n=7;
    int vett[n];
    int i,x,y;
    cout << " insersici " << n << " elementi " << endl;
    for(i=0;i<n;i++)    
    cin >> vett[i];
    cout << "inserisci " << " l'elemento x e poi y " << endl;
    cin >> x >> y;    
    proc(vett,n,x,y);
    system("PAUSE");
    return EXIT_SUCCESS;
}

>Damn i didnt expect it to be that easy LOL!!
Because it's not.

>simply declared another array in the procedure with n+1
n isn't a compile-time constant, and C++ requires that particular attribute for array sizes. Your code is specific to a single compiler and will fail if compiled with another implementation that doesn't support the same extension in the same way. At the very least you need to use a dynamic array or std::vector.

>and copied elements of the array into it!
This fails to meet the original requirement of updating the array (which you claimed to be required and the function signature suggests). You cheated by assuming that callers want the values printed and nothing else. This lesser requirement could easily be met without introducing another array:

void proc ( int vett[],int n, int x, int y )
{
  for ( int i = 0; i < n; i++ ) {
    if ( vett[i] == x )
      cout<< y << x <<' ';

    cout<< vett[i] <<' ';
  }

  cout<<'\n';
}

>here is the code
Either your code doesn't solve the problem, or you completely failed to describe the problem correctly and have been stringing me along on a wild goose chase.

#define ARRAYBLOCKSIZE 3

void addtoarray( int** a, size_t *length, size_t *capacity, int x, int y )
{	
	for( size_t i = 0; i < *length; i++ )		
		if ( (*a)[i] == x )
		{
			if ( *length == *capacity )
			{
				*a = ( int* ) realloc ( 
                                        *a, ( *capacity + ARRAYBLOCKSIZE ) * sizeof(int) );
				*capacity = *capacity + ARRAYBLOCKSIZE;
			}

			(*length)++;
			for( size_t j = *length - 1; j > i; j--  ) (*a)[j]= (*a)[j-1];
			(*a)[i] = y;
			break;
		}			
}

int main(int argc, char* argv[])
{
	size_t capacity = ARRAYBLOCKSIZE;
	int *myarray = (int*)malloc(sizeof(int)*ARRAYBLOCKSIZE);
	myarray[0]  = 0;
	myarray[1] = 1;
	
	size_t length = 2; // => array has one empty slot

	addtoarray( &myarray, &length, &capacity, 1, 5 ); //now length == capacity
	addtoarray( &myarray, &length, &capacity, 9, 7 ); //realloc => capacity = 6
	addtoarray( &myarray, &length, &capacity, 5, 7 );
	printf( "length and capacity are: %d, %d\n", length, capacity );
	for( size_t i = 0; i < length; i++ )
	{
		printf( "array[ %d ] = %d\n",i ,myarray[i] );
	}
}

this is your function
things to note:
-u provide a pointer to the array, pointer to the number of filled array comonents , pointer to it's capacity and the two numbers x and y.
-If the array is full ( lenght == capacity ) then realloc is used to extend it's capacity
- ARRAYBLOCKSIZE is 3 for exemplification. it should be a big value so realloc is called not so often

>this is your function
Seeing as how the definition fails to match the one that ART01 has repeatedly demonstrated as the desired signature, I'd say it's not.

>If the array is full ( lenght == capacity ) then realloc is used to extend it's capacity
Assuming the array was dynamically allocated originally. Reading the first post, it's clear that the OP wants this function to work with a fixed array.

>*a = ( int* ) realloc ( *a, ( *capacity + ARRAYBLOCKSIZE ) * sizeof(int) );
What do you plan to do if realloc fails? As it is, your plan seems to be memory leaks and null pointer dereferencing.

yea, i did a simple implementation without error checking. realloc return value is not checked, true. I did that for simplicity. And don't consider main, it's just a most simple test, no free done. If he wants it to work "fullproof", he can do that on it's own considering he understands what the function actually does.

>You cheated by assuming that callers want the values printed and nothing else.

since its a procedure its not supposed to return any value, its fine if it just prints it.

>you completely failed to describe the problem correctly and have been stringing me along on a wild goose chase.

i tried my best to describe in the best way possible, but since i m new to programming and c++ it might not have been perfect.i appreciate ur advice and help and any confusion was not intentional.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.