Storing strings in a char array

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.00Thanks for any help!

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

#include #include 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 tothe array

See also  How to Avoid Money Transfer Scams  

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist