简体   繁体   中英

Are the values assigned to char array constant by default

If I try to assign values to char array. It gives the error. Error '=': cannot convert from 'const char [5]' to 'char'.
Why the values assigned to char array are always constant?

class Employee
{
public:
    string name;
    char id[100];
    int age;
    long salary;

    Employee()
    {
        name = "NULL";
        id[100]= "NULL";
        age = 0;
        salary = 0;
    };
};

here i can't do assignment as "NULL" is considered as const char. while my id is char. why "NULL" is constant.

while if we individually check then we can change array values.

{
    char i[10]="maha";
    i[1]='z';
    cout<<i[0]<<i[1]<<i[2]<<i[3]<<endl;
}

You're trying to fill maha in the 100th array index of id which is impossible. The array has only 100 indices, you're trying to access an out-of-range index.

Notice that you can initialize a char array during initialization but not during assignment of it.

char i[10] = "maha";

syntax is an initialization, whereas:

char id[100];
id[100] = "maha"; // incorrect

is an assignment.


There are two possible ways to solve it:

Method 1: Use of strcpy() -

strcpy(str, "maha"); // copying the string "maha" into 'legend'

Method 2: Use of pointer and memory allocation -

const int SIZE = 100;
char *str = new char[SIZE];

str = "maha"; // it's now modifable lvalue

In your array total size is 100 (Index 0 - 99) and you are trying to set at index 100 which is out of range.

Here array is char means you can set only one character per index. you can not set id[10] = "maha".

You can initialize array by using memset function as below

memset(&id[0],0x00,sizeof(id))

Use memcpy to update array

memcpy(&id[10], "maha", 4)

Individual character update

id[10] = 'm'
id[11] = 'a'
id[12] = 'h'
id[13] = 'a'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM