Home > Enterprise >  String not assignable to char array in C
String not assignable to char array in C

Time:10-06

Hello I am very new to C and I have a simple question. Why does the second method of assigning a string to char name2[] not work? It causes a compilation error saying "Array type 'char[20]' is not assignable".


int main() {
    char name[20] = "Alex";

    char name2[20];
    name2 = "Alex"; //error!

}

CodePudding user response:

Why does the second method of assigning a string to char name2[] not work? It causes a compilation error saying "Array type 'char[20]' is not assignable".

There is no "second method" presented. This ...

    char name[20] = "Alex";

... does not demonstrate an assignment, but rather an initialization. The = within is not functioning as the assignment operator, but rather as part of the syntax for specifying the initial value that name will take. And yes, this is a common source of confusion for newcomers to C.

On the other side, it is not possible to assign to whole arrays in C (this also is a common source of confusion for newcomers). This is the reason for the compilation error. You can copy the contents of one array into another with, for example, strcpy() or memcpy(), but there are almost no operators that accept arrays as operands. C arrays have more surprises to offer you, too, but I won't spoil them.

Once you understand C's idiosyncratic treatment of arrays, I think you'll see that it's internally consistent. Until then, however, you would do well to be alert whenever you see or use an array.

CodePudding user response:

Arrays do not have the assignment operator. Instead you need to copy the string from one array to another like

#include <string.h>

//...

strcpy( name2, name );

Or just to copy the string literal using the same function strcpy

strcpy( name2, "Alex" );

On the other hand, you can assign the address of the string literal to a pointer like

char *name2;
name2 = "Alex";

In this case you may not change the string literal using the pointer.

CodePudding user response:

Assuming you want to define a different string, and not just copy the previous one (assuming you used the same name as an example), you can use the scanf command:

#include <stdio.h>

int main()
{
    char name[20] = "alex";
    char name2[20];
    
    printf("Type the name: \n");
    scanf("%s", name2);
    printf("name is %s. name2 is %s",name, name2);

    return 0;
}

In this case it will be required an user input (you will need to write the name on the terminal).

  • Related