- The array should be dynamic, but it is fixed.
- Printing the array gives nothing.
I'm trying to create a dynamic char array, get a string line from user, save line string char by char into the array.
#include <iostream>
#include <string>
using namespace std;
int main()
{
char* lenptr = NULL; // declare a pointer initialized with null
int leng, arrsz;
string mystr;
cout << "enter a string: ";
getline(cin, mystr); // input a line of string
leng = mystr.length(); // get length of string
cout << "string length: " << leng << endl;
lenptr = new char[leng+1]; // declare a dynamic char array with length+1
for (int i = 0; i < leng; i++)
{
lenptr[i]=mystr[i]; // fill array with saved string
}
lenptr[leng] = '\0'; // save '\0' in last array cell
arrsz = sizeof(lenptr); // get size of array
cout << "size of array after saving " << leng << " chars: " << arrsz << endl;
cout << "string in array: ";
for (int j = 0; j < leng; j++) // print array
{
lenptr[j];
}
cout << endl;
// delete pointer
delete[] lenptr;
lenptr = NULL;
system("pause"); // pause system
return 0;
}
enter a string: helloworld string length: 10 size of array after saving 10 chars: 8 string in array: Press any key to continue . . .