Home > OS >  Is there any shortcut way to initialize char array which is allocated by new keyword
Is there any shortcut way to initialize char array which is allocated by new keyword

Time:12-31

Like in SMA we initialize char array as char arr[]={"Text"}; How to initialize char type array in DMA i.e, char *ptr = new char[10]; now i don't want to use loop or multiple lines !

#include<iostream>
#include<conio.h>
using namespace std;

int main()
{

char *ptr = new char[10];

for (int i = 0; i < 10; cout << ptr[i], i  )
ptr[i] = getch();

cout<<ptr;

return 0;
}

CodePudding user response:

You can use strcpy to copy a string into a character array that has been allocated using new:

char *ptr = new char[10];
strcpy(ptr, "Text");

CodePudding user response:

Since you're explicitly asking about "initializing", you can do this:

char *ptr = new char[10]{"Text"};

Working demo

  •  Tags:  
  • c
  • Related