简体   繁体   中英

Assigning a string of characters to a char array

I Want to know why the first statements works and why not second one in c++

char a[10]="iqbal";  // it works

a="iqbal"; // does not work 

Strictly speaking, an array is not a pointer! And an array ( base address of the array ) cant be a modifiable lvalue . ie it cannot appear on the left hand side of an assignment operator.Arrays decay into pointers only in certain circumstances. Read this SO post to learn when arrays decay into pointers. Here is one more nice article which explains the differences between arrays and pointers

Also read about lvalues and rvalues here so that you get an idea of things which cannot appear on the LHS of =

char a[10]="iqbal"; // it works

In this case, internally what happens is

a[0] = 'i';
a[1] = 'q'; 
 .
 .
a[5] = '\0';

So everything is fine as array[i] is a modifiable lvalue.

a="iqbal"; // does not work

Internally, this is roughly equivalent to

0x60000(Address of a, but is a simple number here ) = Address of "iqbal"

This is wrong as we cannot assign something to a number.

The char array a will be static and can not be changed if you initialize it like this. Anyway you can never assign a character string a="iqbal" in c. You have to use strncpy or memcpy for that. Otherwise you will try to overwrite the pointer to the string, and that is not what you want.

So the correct code would do something like:

char a[10];
strncpy(a, "iqbal", sizeof(a) - 1);
a[sizeof(a) - 1] = 0;

The -1 is to reserve a byte for the terminating zero. Note, you will have to check for yourself if the string is null terminated or not. Bad api. There is a strlcpy() call that does this for you but it is not included in glibc.

The first line is not a statement but a declaration with an initialization. The second line is an expression statement with the assignment operator.

You cannot assign arrays in C.

But you can initialize an array with the elements of a string literal.

why the first statements works and why not second one in c++

Because they are different statements, almost wholly unrelated. Do not be confused by the fact that they both use the = symbol. In one case, it represents object initialization. In the other case, the assignment operator.

Your first line is legal because it is legal to initialize aggregates, including character arrays.

Your second line is not legal because it is not legal to assign to an array.

Since this is C++, may I suggest that you avoid naked arrays? For character strings use std::string . For other arrays use std::vector . If you do, you example becomes:

std::string a = "iqbal";  // it works
a="iqbal"; // so does this

When writing char a[10]="iqbal" You are initializing the elements of the character array a with the characters. We can do the same with int type (note that the char type gets a slightly different treatment): int a[10]={1,2,...};

But writing the following after declaration part would be invalid as a would be treated just like a pointer. So writing something like a={1,2,...}; or a="iqbal" won't be making any sense!

try:

char a[10]="iqbal";
char *my_a = a;

and work with my_a.

In C++11 you can use a lambda to do the initialization, like so:

bool test = true;
/*const*/ char a[10] = { //Aggregate initialization
                        [=] //capture by value
                           ()//no parameters
                             { //start lambda
    switch (test) {
        case true: return *"test=true"; //*"xxx" don't return a pointer, but the 'string' itself
        case false: return *"test=false"; 
    } //switch
}()};  //}, close the lambda, (), call it, }; close aggregate initialization

This comes in handy when your environment does not support std::string , like NVidia's CUDA or some strange embedded environment. The lambda gets to be inlined, so internally it translates to char a[10] = test?"xxx":"yyy";

If you have the option to do so, you obviously want to always use std::string , because fixed sized char buffers are fundamentally a bad idea.

If you use std::string you can convert that to a char array using: chararray = mystring.c_str(); . Which is useful if you insist on using printf : printf("s = %s", mystring.c_str()); .

You cannot assign a string literal to a char array after the latter's declaration.

A nice, simple & effective alternative is to use std::strcpy to do so, like so:

struct S
{
    char name[30];
};

S s;
std::strcpy( s.name,
    "The moribunds salute you." );

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