Thread: insert a value into an array! Help

  1. #1
    Registered User
    Join Date
    Feb 2004

    insert a value into an array! Help

    For example: a[6]={1, 2, 3, 4, 5, 6}. I want to insert value 7 into a[2] this the output 1, 2, 7, 3, 4, 5. I write a free function like this

    void insert(int a[], int &size, int pos, int number)

    int i;

    for(i=pos;i<size; i++)
    Can you correct function for me? I got uncorrectly output.

  2. #2
    vae victus! skorman00's Avatar
    Join Date
    Nov 2003
    the statement within the for loop should be flipped. Follow it through using your own numbers, and you'll see that you are setting the next position to the position behind you.

    You may also need to change the condition of your for loop to stop you from going out of bounds of the array depending and what you pas in as size.

  3. #3
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Try passing an int* instead of int[], though I don't know if that's the problem. Also, if size is the size of the array, that might be another problem: a[i + 1] = a[i]. Since i goes up to (size - 1), i + 1 will eventually be (size), which should give an array index out of bounds. Try those and see if it helps

    Oops, good point skorman. The for loop should iterate backwards (go from (size - 1) to pos) if you want it to work.
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  4. #4
    Registered User
    Join Date
    Feb 2004
    Thanks, Hunter and Skorman00

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Insert value into array
    By Salgat in forum C Programming
    Replies: 6
    Last Post: 02-27-2009, 06:50 PM
  2. Code: An auto expanding array (or how to use gets() safely).
    By anonytmouse in forum Windows Programming
    Replies: 0
    Last Post: 08-10-2004, 12:13 AM
  3. Merge sort please
    By vasanth in forum C Programming
    Replies: 2
    Last Post: 11-09-2003, 12:09 PM
  4. insert an element i array
    By planet_abhi in forum C Programming
    Replies: 6
    Last Post: 02-22-2003, 07:04 PM
  5. Creating 2D arrays on heap
    By sundeeptuteja in forum C++ Programming
    Replies: 6
    Last Post: 08-16-2002, 11:44 AM