Assigning a string of characters to a char array

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.

Tags:

C++