Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Jul 18, 1997



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Storing strings in a char array

This is actually a simpler form of the real problem I am dealing with. I have a array of char like so:
char name[20];
Then, I try to put a string in it:
This doesn't work; it gives an error.

I know could do this:

char name[20]="George";
which does work, but I want to change the contents as the program runs. Is this possible? I am a beginner using Borland TC++ v3.00 Thanks for any help!

Char arrays are considered to have a const type, hence their value cannot be changed once created. The value of the data that they point to can, however, be changed. In case of char arrays you can use the standard C function strncpy. Here is an example.


void foo ()
   char charArray [20];
   char another[30];

   cin >> another;
   strncpy (charArray,another,20);
This example reads a string from the standard input and copies it to the array
DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date