Adding nodes to an array at the top & array sorting

This is a discussion on Adding nodes to an array at the top & array sorting within the C++ Programming forums, part of the General Programming Boards category; A friend asked me to edit this for him, and quite frankly, I have no idea how to do it. ...

  1. #1
    Registered User
    Join Date
    Jun 2009
    Posts
    30

    Adding nodes to an array at the top & array sorting

    A friend asked me to edit this for him, and quite frankly, I have no idea how to do it. He wants me to make the function add new data to the top of the array, rather than the bottom, and can be sorted highest to lowest. So, here's the code for the function:

    Code:
    void ptrlist::add(char* item)
    {
    	if ((length * 4) == buffSize)
    	{
    		char** temp = new char*[buffSize + 6];
    		
    		if (temp == 0)
    			return;
    
    		buffSize += 6;
    		memcpy(temp, buff, length * 4);
    
    		delete[] buff;
    
    		buff = temp;
    	}
    
    	buff[length] = item;
    
    	length++;
    }

  2. #2
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,473
    1. new does not returns null - instead it throws exception when out of memory

    you need to use nothrow version to use it like this

    2. your code asumes that sizeof(char*) is 4 - this makes it non-portable

    3. if you need a list - just use std::list and leave the memory management to it.

    with the list it will be really easy to add data atthe beginning - instead of need to move all the array on each append to free the slot at the beginning
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 12
    Last Post: 03-11-2010, 01:28 PM
  2. adding elements in array
    By reb221 in forum C Programming
    Replies: 6
    Last Post: 12-30-2008, 01:41 PM
  3. Array Sorting problem
    By ___________ in forum C++ Programming
    Replies: 4
    Last Post: 07-22-2008, 12:17 AM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 09:33 AM
  5. Stack functions as arrays instead of node pointers
    By sballew in forum C Programming
    Replies: 8
    Last Post: 12-04-2001, 10:13 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21