Please Help me In C++

Mar 12, 2012
14
0
Hello Friends,


I want to create the dynamic array in C++ . Please suggest me guys .
How i create the dynamic array in C++ .
 
Hello Friends,


I want to create the dynamic array in C++ . Please suggest me guys .
How i create the dynamic array in C++ .
Impossible. You have two options
1. recreate new one each time element is added, copying whole old array to new one and toss the old (size of the new should be old+added)--NOT RECOMMENDED
2. Use std::vector which have become standard to solve the problem -- RECOMMENDED

Example using vector (since I recommended)
Code:
#include <iostream>
#include <vector>


int main()
{
    std::vector<std::string> names;
    std::cout<<"-------------------------\n";
    names.push_back("Jamii");
    names.push_back("Forums");
    //see what is in so far
    for(int i=0; i<names.size(); i++)
        std::cout<<names.at(i)<<"\n";
    std::cout<<"Now After adding dynamically\n-------------------------\n";
    names.push_back("CTO");
    //see what is in after adding dynamically
    for(int i=0; i<names.size(); i++)
        std::cout<<names.at(i)<<"\n";
        
    return 0;
}
compiling:
g++ -o testvector example.cpp

then run file named testvector in Linux or testvector.exe in windows

I Used GCC so check flags for VC or any other compile (hopeful not Borland TurboC).

OUTPUT
-------------------------
Jamii
Forums
Now After adding dynamically
-------------------------
Jamii
Forums
CTO
 
CTO it is not impossible.the guy has to use dynamic memory allocation functions.alloc and malloc thats all.
 
CTO it is not impossible.the guy has to use dynamic memory allocation functions.alloc and malloc thats all.

PakavuNateleza
Can you show an example of its possibility?In C/C++ there is no dynamic array per se. Using malloc will only fulfill possibility 1 in my answer. That is each time you append/insert new value your version of "dynamic" array have to copy the old contents and its indices, destroy current array, create new array with new size, add old elements and append the new one. It is time consuming and poor perfomance is unavoidable. That's why I did not recommend it (Except for class assignments).

Use STL vectors. They were invented to be used that way!

See the C++ Manual on malloc
void * malloc ( size_t size );

Allocate memory block
Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.

The content of the newly allocated block of memory is not initialized, remaining with indeterminate values.

If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be used to dereference an object in any case.
Manual is at http://www.cplusplus.com/reference/cstdlib/malloc/
 
Last edited by a moderator:
PakavuNateleza
Can you show an example of its possibility?In C/C++ there is no dynamic array per se. Using malloc will only fulfill possibility 1 in my answer. That is each time you append/insert new value your version of "dynamic" array have to copy the old contents and its indices, destroy current array, create new array with new size, add old elements and append the new one. It is time consuming and poor perfomance is unavoidable.
Remember it will no longer be an array, you will need class that will encapsulate all these functionalities. STL library is optimum solution (purposely repeated!)
 
Last edited by a moderator:
Remember it will no longer be an array, you will need class that will encapsulate all these functionalities. STL library is optimum solution (purposely repeated!)

Not necessary need to have a class C.T.O.Eg. You could create data structure(let say students profile) and dynamically add or remove students from list(array of students profile).Remember Linked List in Data structure and this is where you have to use the malloc,malloc and free. This is what happened in a nutshell to achieve a dynamic memory allocation and de-allocation. In OOP all these has been encapsulated in classes and do the memory management for you.
 
Not necessary need to have a class C.T.O.Eg. You could create data structure(let say students profile) and dynamically add or remove students from list(array of students profile).Remember Linked List in Data structure and this is where you have to use the malloc,malloc and free. This is what happened in a nutshell to achieve a dynamic memory allocation and de-allocation. In OOP all these has been encapsulated in classes and do the memory management for you.
Its time to roll sleeves and write us a simple example.
Can you toss one example to demonstrate your dynamic array without class (or struct for that matter)? And remember you are trying to correct my post so take that into consideration!
 
Its time to roll sleeves and write us a simple example.
Can you toss one example to demonstrate your dynamic array without class (or struct for that matter)? And remember you are trying to correct my post so take that into consideration!


Since you insist.Then this it is.

Note Most important function are the one to create space,add to List and delete list to reclaim Memory.


Code:
#include <stdio.h>
#include <alloc.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>

/* function prototypes */
struct node * initnode( char *, int );
void printnode( struct node * );
void printlist( struct node * );
void add( struct node * );
struct node * searchname( struct node *, char * );
void deletenode( struct node * );
void insertnode( struct node * );
void deletelist( struct node * );


/* Hapa nadefine data structure yangu ya kuhold students information */

struct node {
   char name[20];
   int  id;
   struct node *next;
};

/* Nadefine pointer mbili ya kuhold position ya first node na last node for student list */
/* initialise both to NULL, meaning no nodes in list yet */

struct node *head = (struct node *) NULL;
struct node *end = (struct node *) NULL;


void main()
{
   char name[20];
   int id, ch = 1;
   struct node *ptr;

   clrscr();

  //Menu ya kudemonstrate dynamic Memory allocation and de-allocation.

   while( ch != 0 ) {
      printf("1 add a name \n");
      printf("2 delete a name \n");
      printf("3 list all names \n");
      printf("4 search for name \n");
      printf("5 insert a name \n");
      printf("0 quit\n");
      scanf("%d", &ch );
      switch( ch )
      {
          case 1:  /* add a name to end of list */
                   printf("Enter in name -- ");
                   scanf("%s", name );
                   printf("Enter in id -- ");
                   scanf("%d", &id );
                   ptr = initnode( name, id ); //Hii function ina add memory space dynamically
                   add( ptr );         //Hii function inaweka std information to the allocated memory above
                   break;
          case 2:  /* delete a name */
                   printf("Enter in name -- ");
                   scanf("%s", name );
                   ptr = searchname( head, name );
                   if( ptr ==NULL ) {
                       printf("Name %s not found\n", name );
                   }
                   else
                      deletenode( ptr );
                   break;

          case 3:  /* list all nodes */
                   printlist( head );
                   break;

          case 4:  /* search and print name */
                   printf("Enter in name -- ");
                   scanf("%s", name );
                   ptr = searchname( head, name );
                   if( ptr ==NULL ) {
                       printf("Name %s not found\n", name );
                   }
                   else
                      printnode( ptr );
                   break;
          case 5:  /* insert a name in list */
                   printf("Enter in name -- ");
                   scanf("%s", name );
                   printf("Enter in id -- ");
                   scanf("%d", &id );
                   ptr = initnode( name, id );
                   insertnode( ptr );
                   break;

      }
   }




struct node * initnode( char *name, int id )
{
   struct node *ptr;
   ptr = (struct node *) calloc( 1, sizeof(struct node ) );  //this is where we get the memory
   if( ptr == NULL )                       
       return (struct node *) NULL;        
   else {                                  
       strcpy( ptr->name, name );          
       ptr->id = id;                       
       return ptr;                         
   }
}


/* this adds a node to the end of the list.  */
/* then pass its address to this function                                 */
void add( struct node *new )  /* adding to end of list */
{
   if( head == NULL )      /* if there are no nodes in list, then         */
       head = new;         /* set head to this new node                   */
   end->next = new;        /* link in the new node to the end of the list */
   new->next = NULL;       /* set next field to signify the end of list   */
   end = new;              /* adjust end to point to the last node        */
}


/* deletes the specified node pointed to by 'ptr' from the list           */
/*Hapa tuna de-allocate memory from list.
void deletenode( struct node *ptr )
{
   struct node *temp, *prev;
   temp = ptr;    /* node to be deleted */
   prev = head;   /* start of the list, will cycle to node before temp    */

   if( temp == prev ) {                    /* are we deleting first node  */
       head = head->next;                  /* moves head to next node     */
       if( end == temp )                   /* is it end, only one node?   */
          end = end->next;                 /* adjust end as well          */
       free( temp );                       /* free space occupied by node */
   }
   else {                                  /* if not the first node, then */
       while( prev->next != temp ) {       /* move prev to the node before*/
           prev = prev->next;              /* the one to be deleted       */
       }
       prev->next = temp->next;            /* link previous node to next  */
       if( end == temp )                   /* if this was the end node,   */
           end = prev;                     /* then reset the end pointer  */
       free( temp );                       /* free space occupied by node */
   }
}




/* this prints the details of a node, eg, the name and id                 */
/* must pass it the address of the node you want to print out             */
void printnode( struct node *ptr )
{
   printf("Name ->%s\n", ptr->name );
   printf("ID   ->%d\n", ptr->id );
}

/* this prints all nodes from the current address passed to it. If you    */
/* pass it 'head', then it prints out the entire list, by cycling through */
/* each node and calling 'printnode' to print each node found             */
void printlist( struct node *ptr )
{
   while( ptr != NULL )           /* continue whilst there are nodes left */
   {
      printnode( ptr );           /* print out the current node           */
      ptr = ptr->next;            /* goto the next node in the list       */
   }
}


/* search the list for a name, and return a pointer to the found node     */
/* accepts a name to search for, and a pointer from which to start. If    */
/* you pass the pointer as 'head', it searches from the start of the list */
struct node * searchname( struct node *ptr, char *name )
{
    while( strcmp( name, ptr->name ) != 0 ) {    /* whilst name not found */
       ptr = ptr->next;                          /* goto the next node    */
       if( ptr == NULL )                         /* stop if we are at the */
          break;                                 /* of the list           */
    }
    return ptr;                                  /* return a pointer to   */
}                                                /* found node or NULL    */


/* inserts a new node, uses name field to align node as alphabetical list */
/* pass it the address of the new node to be inserted, with details all   */
/* filled in                                                              */
void insertnode( struct node *new )
{
   struct node *temp, *prev;                /* similar to deletenode      */

   if( head == NULL ) {                     /* if an empty list,          */
       head = new;                          /* set 'head' to it           */
       end = new;
       head->next = NULL;                   /* set end of list to NULL    */
       return;                              /* and finish                 */
   }

   temp = head;                             /* start at beginning of list */
                      /* whilst currentname < newname to be inserted then */
   while( strcmp( temp->name, new->name) < 0 ) {
          temp = temp->next;                /* goto the next node in list */
          if( temp == NULL )                /* dont go past end of list   */
              break;
   }

   /* we are the point to insert, we need previous node before we insert  */
   /* first check to see if its inserting before the first node!          */
   if( temp == head ) {
      new->next = head;             /* link next field to original list   */
      head = new;                   /* head adjusted to new node          */
   }
   else {     /* okay, so its not the first node, a different approach    */
      prev = head;   /* start of the list, will cycle to node before temp */
      while( prev->next != temp ) {
          prev = prev->next;
      }
      prev->next = new;             /* insert node between prev and next  */
      new->next = temp;
      if( end == prev )             /* if the new node is inserted at the */
         end = new;                 /* end of the list the adjust 'end'   */
   }
}

/* this deletes all nodes from the place specified by ptr                 */
/* if you pass it head, it will free up entire list                       */
void deletelist( struct node *ptr )
{
   struct node *temp;

   if( head == NULL ) return;   /* dont try to delete an empty list       */

   if( ptr == head ) {      /* if we are deleting the entire list         */
       head = NULL;         /* then reset head and end to signify empty   */
       end = NULL;          /* list                                       */
   }
   else {
       temp = head;          /* if its not the entire list, readjust end  */
       while( temp->next != ptr )         /* locate previous node to ptr  */
           temp = temp->next;
       end = temp;                        /* set end to node before ptr   */
   }

   while( ptr != NULL ) {   /* whilst there are still nodes to delete     */
      temp = ptr->next;     /* record address of next node                */
      free( ptr );          /* free this node                             */
      ptr = temp;           /* point to next node to be deleted           */
   }
}

/* this is the main routine where all the glue logic fits                 */

   deletelist( head );
}
 
Since you insist.Then this it is.

Note Most important function are the one to create space,add to List and delete list to reclaim Memory.
Well that is the best way of "talking"

Code:
struct node {
   char name[20];
   int  id;
   struct node *next;
}; 

struct node * initnode( char *name, int id )
{
   struct node *ptr;
   ptr = (struct node *) calloc( 1, sizeof(struct node ) );  //this is where we get the memory
   if( ptr == NULL )                       
       return (struct node *) NULL;        
   else {                                  
       strcpy( ptr->name, name );          
       ptr->id = id;                       
       return ptr;                         
   }
}
Well, well, my point proven!
You have proved very well my answers that
1. dynamic array is impossible
2. There is possibility to "emulate it"
3. To do emulation, you need either struct or class to encapsulate the data structure functionalities

I guess you misunderstood my answers!
 
I like the way code is indented: neat and well commented. Are you coming from Python background?
 
I like the way code is indented: neat and well commented. Are you coming from Python background?

No. I started with C/C++ at University, Did a lot of Java and now I do a Lot of PHP in web development and C# for Desktop applications.

How about you?
 
No. I started with C/C++ at University, Did a lot of Java and now I do a Lot of PHP in web development and C# for Desktop applications.

How about you?
Don't hit me, but C# is one of languages I hate to work with. PHP is lovely Indian elephant. You go to marriage with no problem.
Do you use Mono for Linux or you just develop in single platform? If you don't mind, do you work with PHP frameworks?
 
Don't hit me, but C# is one of languages I hate to work with. PHP is lovely Indian elephant. You go to marriage with no problem.
Do you use Mono for Linux or you just develop in single platform? If you don't mind, do you work with PHP frameworks?

I like to develop my application in windows.When the cooking is ready I do host most of applications (Web based one) in Linux Environment.
On PHP Framework I mainly use Yii Framework plus a bit of Zend framework on areas that I think zend will do better.
 
I like to develop my application in windows.When the cooking is ready I do host most of applications (Web based one) in Linux Environment.
On PHP Framework I mainly use Yii Framework plus a bit of Zend framework on areas that I think zend will do better.
Good to know you use Yii. Something is on the cookery, once it is ready I will inform you.
Stay blessed!
BH
 

Similar Discussions

0 Reactions
Reply
Back
Top Bottom