C++ stack using class

This is a discussion on C++ stack using class within the C++ Programming forums, part of the General Programming Boards category; hi guys, im trying to figure out why my program is not working, it's not finished yet, but i cant ...

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    72

    C++ stack using class

    hi guys, im trying to figure out why my program is not working, it's not finished yet, but i cant understand why its not working until now

    Code:
    //stack with integers
    
    #include <iostream>
    
    using namespace std;
    
          
          
    class stack{
          int pos;
          int *a;
          int check;
          public:
                 stack();
                 void freestack();
                 void add(int);
                      
          };
          
    stack::stack(){
    
                         check = 1;
                         a = new int[10];
                         cout<<"array of 10 has been created..."<<endl;
                         pos = 0;
    
                         }
    
    void stack::freestack(){
    
                            delete[] a;
    
                            }
    void stack::add(int n){
    
                   if (pos<check*10){
    
                      *(a+pos) = n;
                      pos++;
                      cout<<"New integer added"<<endl;
    
                      }
    
                   else {
    
                           a = (int *)realloc(a,++check*10*sizeof(int)); // idont know how to do this in c++
    
                           if (a!=NULL){
                                        cout<<"More memory assigned\n"<<endl;
                                        pos++;
                                        a[pos]=n;
                                        cout<<"New integer added"<<endl;
                                        }
    
                           }
    
             }
    int main(void){
        
        stack newstack;
        newstack.freestack();
        newstack.add(1);
        system("pause");
        
        
        return 0;
    }
    i think that the problem is in this line

    Code:
    a[pos] = n;
    because when i comment this line then the program works fine, i cant understand why its not working there

    I mean I have the pos variable which is private, so is the array, i have allocated 40 bytes in the constructor and the a variable points to the first element of the allocated memory in heap

    but why doesnt this work?

    thanks in advance
    Last edited by nik2; 05-24-2010 at 02:54 PM.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,456
    It looks like you never actually initialise pos to anything. By the way, you really need to indent your code properly.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Feb 2010
    Posts
    72
    doesnt it get initialized in the constructor?

    Edit: sorry for the code i made it very quickly

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,456
    Quote Originally Posted by nik2
    doesnt it get initialized in the constructor?
    Oh, no it does not, since you failed to use the constructor initialisation list. But it does get assigned to in the constructor, so that is probably not the problem. The next problem might lie with how you are expanding the dynamic array: you increment pos prematurely.

    Oh, and speaking of that, I suggest that you avoid the use of malloc, realloc and free here. You may want to extend this exercise to objects of class types, upon which the use of these functions in this way would be incorrect. Use new[] and delete[] instead. Actually, it would be even easier to use a std::deque<int> like std::stack so as to concentrate on getting the stack operations right instead of also dealing with dynamic memory allocation at the same time.

    Before making any further replies, fix your indentation. Now.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    Feb 2010
    Posts
    72
    i edited the code but im not sure if thats what you mean when you say "indentation"

    after i changed the malloc and free the result is the same i get the same problem
    Last edited by nik2; 05-24-2010 at 02:57 PM.

  6. #6
    Registered User
    Join Date
    Feb 2010
    Posts
    72
    ok i think i have it correct right now


    i made 3 different files, main.cpp has the main function, stack.h has the class and functions.cpp has the class functions

    im not sure about the realloc though, i dont know if there is a function for this, but i made one that does a similar job
    sorry for replying so late, i forgot this problem

    Edit: oh, i should have made the reallok function private
    Attached Files Attached Files
    Last edited by nik2; 06-04-2010 at 08:01 AM.

  7. #7
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,455
    Google isn't an option for you? Indent style - Wikipedia, the free encyclopedia
    Again, forget about realloc. Use a vector. Realloc should not, must not be used with new and delete.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  8. #8
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    You can use realloc if you want, just don't use it on variables initialized with new (only with malloc) and use free() on them, not delete.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  9. #9
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,455
    Don't use realloc in C++ at all. Use new and delete.
    But you don't even need them here. They're tricky and should be avoided.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    Registered User
    Join Date
    Feb 2010
    Posts
    72
    Quote Originally Posted by Elysia View Post
    Google isn't an option for you? Indent style - Wikipedia, the free encyclopedia
    Again, forget about realloc. Use a vector. Realloc should not, must not be used with new and delete.
    actually thats the first thing i saw about indentation, i hope i have it correct in the files

    Edit: about the realloc, yea when i used it it didnt work at all, im new to C++ i dont know anything about vectors yet, that's why i created a reallok that does a similar job with realloc

    i ll definitely search for vectors later on, thanks for your help guys
    Last edited by nik2; 06-04-2010 at 08:17 AM.

  11. #11
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Elysia View Post
    Don't use realloc in C++ at all.
    You can if you want Not to say that is wise or recommended, just that there is nothing strictly "wrong" about it other than (some people's ideas about) style.

    Calling new and delete tricky is like calling shoe tying dangerous. Remember to use a bow and make sure the ends do not touch the ground and you'll be fine.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  12. #12
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,455
    We're talking about a newbie here. I would not recommend new and delete to a newbie. Dangerous stuff. Easy to shoot yourself in the foot. So easy to create bugs. Use already proven working solutions if you can!
    And while realloc is not Evil™, do not recommend it to a newbie. There are areas where it might be needed, but never for pure C++ and especially not for a learner of the language. Dangerous things.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  13. #13
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,638
    You can if you want Not to say that is wise or recommended, just that there is nothing strictly "wrong" about it other than (some people's ideas about) style.
    Well it can be wrong. Particularly when you mix C's flavor of this with C++. new and delete do not have to be implemented in terms of malloc and free, (and AFAIK aren't) so if you just realloc something from new somewhere, you might end up with two different allocations, or worse.

  14. #14
    ...and never returned. StainedBlue's Avatar
    Join Date
    Aug 2009
    Posts
    168
    pushing and popping at an index does not a stack make.

    what the heck is freestack() and reallok()?

    Here are the signatures of the functions you need to implement:

    Code:
    Stack();    // should initialize a pointer, and the value of size
    ~Stack();    // pops until empty
    
    void push(int);    // adds *something* to the top, move pointers around
    
    void pop();    // takes no argument, removes the top, move pointers around
    
    int top();    // returns the int at the top of the stack
    
    int size();    // returns the value of size
    
    bool empty();    // returns true of false (hint: use size)


    EDIT: Here's a few more hints to save time:

    The private members stack needs:
    Code:
    Node* top;
    int size;
    
    // ... And a node struct...
    
    struct
    {
        int data;
        Node* next;
    };
    I leave the rest to you
    Last edited by StainedBlue; 06-04-2010 at 03:37 PM.
    goto( comeFrom() );

  15. #15
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,455
    I would make pop return the element that is removed and rename top to peek. I don't know why they did it like this in STL, but frankly, it's annoying and peek/pop is pretty much standard anyway.
    And StainedBlue, as we have already tried to explain, the OP should not be using dynamic memory at this point. A stack does not need dynamic memory. A vector or a deque should suffice here. Let's not try to put out different solutions here. It will only serve to confuse.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  2. Need Help with Stack
    By trongsi in forum C++ Programming
    Replies: 9
    Last Post: 05-23-2006, 04:14 PM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. structure vs class
    By sana in forum C++ Programming
    Replies: 13
    Last Post: 12-02-2002, 06:18 AM
  5. What am I doing wrong, stack?
    By TeenyTig in forum C Programming
    Replies: 2
    Last Post: 05-27-2002, 02:12 PM

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