I get no error when I type
char a[10] = "Hi";
But when I change it to the following, I get an error: Array type char is not assignable.
char a[10];
a = "Hi";
Why is array type char not assignable? Is it because the language is written that way on purpose or am I missing a point?
The first is an initialization, the second is an assignment. The first line allocates enough space on the stack to hold 10 characters, and initializes the first three of those characters to be 'H', 'i', and '\0'. From this point on, all a does is refer to the position of the the array on the stack.
To assign int value to a char variable in Java would consider the ASCII value and display the associated character/ digit. Here, we have a char. char val; Now assign int value to it.
To copy String1 char array to String2 char array, you cannot simply assign the whole array to it, it has to be copied one character at a time within a loop, or use a string copy function in the standard library.
We can get the corresponding ASCII value of a character by using int() when we print it. We can assign an ASCII value (from 0 to 127) to the char variable rather than the character itself.
While creating variables first of all we will declare them, initialize them, assign/re-assign values to them. You can initialize the array by assigning values to all the elements one by one using the index − When we assign primitive values of one type to a variable of other (datatype) implicitly they are converted.
Once you have an initialized array, the only thing you can do with it is read values from it and write values to it. You can't change its location or size. That's what an assignment would try to do in this case. Show activity on this post. The language does not allow assigning string literals to character arrays.
The C++ way of doing this, as I commented above, would be to use std::string instead of char []. That will give you the assignment behavior you're expecting. That said, the reason you're only getting an error for the second case is that the = in these two lines mean different things:
Because the array is just a place on the stack, a is never allowed to change. If you want a different location on the stack to hold a different value, you need a different variable.
An array is not a modifiable lvalue
use
char a[10];
strcpy(a, "Hi");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With