How can I memory N words using only pointers[Dynamic Memory] ?

I tried something but I believe it's not well coded.

#include<iostream>

    using namespace std;


         int main ()
         {
             char **a;
             int N;
             cout<<"Enter the number of words = ";
             cin>>N;

             for(int i=0;i<N;i++)
               {
                   cout<<"Enter word number "<<i<<" : ";
                   cin.get(*(a+i),....);  
        // where is ... is the lenght of the word ,and I don't know how to determine it.
                   cin.get();
               }


                return 0;

             }

Can you please help me ?

Recommended Answers

All 3 Replies

No, this won't work, you are correct. What you'll need to do is have a large buffer to read the C-string into, then get the size of the string using strlen() , and only then should you allocate the memory to hold the word. Alternately, you can use the string class and avoid the issue entirely.

Schoil-R-LEA can you show me please a example of a code that can memory N words using only pointers[Dynamic Memory] ?

I could, but WaltP would jump all over me for it :P

Seriously, yes, but you have to keep in mind that this is only an example; it doesn't really do much other than repeat back the words. I used your existing code as a framework for the example.

#include <iostream>
#include <cstring>

using namespace std;

int const BUFSIZE = 256;     // use an arbitrarily large buffer that is unlikely to get overrun

int main ()
{
    char buffer[BUFSIZE];
    char **a;
    int N;
    cout<<"Enter the number of words = ";
    cin>>N;
    cin.ignore();    // clear out the excess characters from the buffer
    a = new char*[N]; // allocate the array of strings

    for(int i=0; i<N; i++)
    {
        cout<<"Enter word number "<<i<<" : ";
        cin.get(buffer, BUFSIZE);
        
        int size = strlen(buffer);  // get the size of the string 
        a[i] = new char[size + 1];  // allocate enough space for the string and it's delimiter
        strcpy(a[i], buffer);       // copy the string from the buffer to the new char array
        cin.ignore();
    }

    for(int i=0; i<N; i++)
    {
        cout << a[i] << endl;       // print out the word
        delete[] a[i];
    }

    delete[] a;
    return 0;

}
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.