dynamic memory allocation for charector

please provide me the syntax to do dynamic memory allocation for charector array.
like program which ask to enter the text and the the text get displayed.
you don't need dynamic allocation for that ? anyways :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main ()
{
    const int BUFFER = 256;

    char* pChar = new char[ BUFFER ];

    std::cout << "Enter your name: ";
    std::cin.getline( pChar, 256 );

    std::cout << "Your name is: " << pChar;

    delete [] pChar;
}

i haven't tested this yet

NOTE !!!

you should not use the code above unless you really want it to be cumbersome and error prone later,
what you should do is to use std::string instead when working w/ char arrays :

http://www.cprogramming.com/tutorial/string.html
sorry my ques wasn't that.
i have to just do dynamic memory allocation for char without asking for no of charecters users want...

#include <iostream>

int main ()
{
char* a;
gets(a); \\but it gives run time error
i=strlen(a);
a=new char[i];
puts(a);
getch();
}
based on your code above, i think you want to allocate memory after the user had entered the string, w/c is not possible.

You should allocate memory first before you store something in it.

The possible alternatives is either like my example code or use a std::string instead;

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>

using namespace std;

int main ()
{
    string name; // this is like a series of char
    cout << "Enter your name: ";
    getline( cin, name ); // alternative to gets()
    
    cout << "Hi, " << name;
}
Topic archived. No new replies allowed.