#include <stdio.h>
int main(void) {
int arr[10];
arr = "Hello";
printf("%s",arr);
return 0;
}
The above code shows compiler error:
t.c: In function ‘main’:
t.c:5:9: error: assignment to expression with array type
arr = "Hello";
^
t.c:6:12: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int *’ [-Wformat=]
printf("%s",arr);
^
Whereas the below code works fine.
#include <stdio.h>
int main(void) {
char arr[10] = "Hello";
printf("%s",arr);
return 0;
}
Both look identical to me. What am I missing here?
asked Jan 27, 2017 at 8:21
6
They are not identical.
First of all, it makes zero sense to initialize an int
array with a string literal, and in worst case, it may invoke undefined behavior, as pointer to integer conversion and the validity of the converted result thereafter is highly platform-specific behaviour. In this regard, both the snippets are invalid.
Then, correcting the data type, considering the char
array is used,
-
In the first case,
arr = "Hello";
is an assignment, which is not allowed with an array type as LHS of assignment.
-
OTOH,
char arr[10] = "Hello";
is an initialization statement, which is perfectly valid statement.
knittl
235k52 gold badges307 silver badges356 bronze badges
answered Jan 27, 2017 at 8:23
Sourav GhoshSourav Ghosh
132k16 gold badges184 silver badges258 bronze badges
5
Don’t know how your second code is working (its not working in my case PLEASE TELL ME WHAT CAN BE THE REASON) it is saying: array of inappropriate type (int) initialized with string constant
Since you can’t just assign a whole string
to a integer
variable.
but you can assign a single character
to a int
variable like:
int a[5]={'a','b','c','d','d'}
answered Jan 27, 2017 at 8:30
“Error: assignment to expression with array type” is a common error related to the unsafe assignment to an array in C. The below explanations can help you know more about the cause of error and solutions.
This error happens due to the following reasons:
First, the error happens when attempting to assign an array variable. Technically, the expression (called left-hand expression) before the assignment token (‘=’) has the type of array, and C language does not allow any assignment whose left-hand expression is of array type like that. For example:
#include <stdio.h> int main() { char arr [13]; arr = "LearnShareIT"; printf("%s",arr); return 0; }
Or another example:
#include <stdio.h> int main() { int numbers[4]; numbers = 123; return 0; }
Output:
error: assignment to expression with array type
The example above shows that the left hand of the assignment is the arr variable, which is of the type array declared above. However, the left type does not have to be an array variable. Instead, it can be a call expression that returns an array, such as a string:
#include <stdio.h> int main() { "LearnShareIT" = 99999; return 0; }
Output:
error: assignment to expression with array type
In C, the text that is put between two double quotes will be compiled as an array of characters, not a string type, just like other programming languages.
How to solve the error?
Solution 1: Using array initializer
To solve “error: assignment to expression with array type” (which is because of the array assignment in C) you will have to use the following command to create an array:
type arrayname[N] = {arrayelement1, arrayelement2,..arrayelementN};
For example:
#include <stdio.h> int main() { int array[4] = {1,2,3,4}; printf("%d",array[2]); return 0; }
Output:
3
Another example:
#include <stdio.h> int main() { char array[13] = "LearnShareIT"; printf("%s",array); return 0; }
Output:
LearnShareIT
The first example guides you to create an array with 4 given elements with the value 1,2,3,4 respectively. The second example helps you create an array of char type, each char is a letter which is same as in the string in the double quotes. As we have explained, a string in double quotes is actually of array type. Hence, using it has the same effects as using the brackets.
Solution 2: Using a for loop
Sometimes you cannot just initialize an array because it has been already initialized before, with different elements. In this case, you might want to change the elements value in the array, so you should consider using a for loop to change it.
#include <stdio.h> #include <stdlib.h> int main() { char array[13] = "xxxxxxxx"; char copyarray[13] = "LearnShareIT"; for (int i = 0; i < 13; i++){ array[i] = copyarray[i]; } printf("%s",array); return 0; }
Output:
LearnShareIT
Or, if this is an integer array:
#include <stdio.h> int main() { int array[4] = {1,2,3,4}; int copyarray[4] = {5,6,7,8}; for (int i=0; i<4; i++) array[i] = copyarray[i]; for (int i=0; i<4; i++) printf("%d", array[i]); return 0; }
Output:
5678
When you want to change the array elements, you have to declare a new array representing exactly the result you expect to change. You can create that new array using the array initialiser we guided above. After that, you loop through the elements in that new array to assign them to the elements in the original array you want to change.
Summary
We have learned how to deal with the error “error: assignment to expression with array type” in C. By avoiding array assignment, as long as finding out the reasons causing this problem in our tutorial, you can quickly solve it.
Maybe you are interested:
- Undefined reference to ‘pthread_create’ in Linux
- Print Char Array in C
I’m Edward Anderson. My current job is as a programmer. I’m majoring in information technology and 5 years of programming expertise. Python, C, C++, Javascript, Java, HTML, CSS, and R are my strong suits. Let me know if you have any questions about these programming languages.
Name of the university: HCMUT
Major: CS
Programming Languages: Python, C, C++, Javascript, Java, HTML, CSS, R
killthis 0 / 1 / 1 Регистрация: 07.10.2017 Сообщений: 86 |
||||
1 |
||||
07.04.2018, 23:26. Показов 7752. Ответов 3 Метки нет (Все метки)
Прошу прощения, но почему ругается компилятор, а именно error: assignment to expression with array type
Спасибо
__________________
0 |
Модератор 33875 / 18902 / 3981 Регистрация: 12.02.2012 Сообщений: 31,694 Записей в блоге: 13 |
|
08.04.2018, 06:40 |
2 |
Прошу прощения, а где именно он «ругается»? Скорее всего в месте вида Что-то = Чему-то, где Что-то — массив. В С это недопустимо.
0 |
0 / 1 / 1 Регистрация: 07.10.2017 Сообщений: 86 |
|
08.04.2018, 09:12 [ТС] |
3 |
Проститет, стоило указать строчки: 122, 129, 136.
0 |
likehood 1270 / 1027 / 470 Регистрация: 25.12.2016 Сообщений: 3,333 |
||||
08.04.2018, 10:56 |
4 |
|||
char name[MAX] Это статический массив фиксированной длины (MAX). Память под него уже выделена компилятором.
pinf->name=(char*)malloc(strlen(buf_name)+1); //ЗДЕСЬ А здесь вы пытаетесь работать с ним как с динамическим массивом, что разумеется неверно. Если нужен именно динамический массив, объявить name как указатель:
0 |
The error: assignment to expression with array type is a common sight. The main cause is that it shows the error as not assignable due to the value associated with the string. That value is not directly feasible in C.
To solve this, a normal strcpy() function is used for the modification of the value. In this guide, we’ll review some possible ways to get around this issue by using relevant examples.
Contents
- Why Is the “Error: Assignment to Expression With Array Type” Error Happening?
- – Using Un-assignable Array Type
- – The Block of Memory Is Below 60 Chars
- – Not Filling the Struct With Pointers
- – Syntax Error
- – Directly Assigned a Value to a String
- – Trying To Change the Constant
- How To Fix “Error: Assignment to Expression With Array Type” Error?
- – Use Assignable Array Type
- – Use Strcpy() To Copy Into the Array
- – Block of Memory That Fits 60 Chars
- – Fill the Structure With Pointers
- – Use Correct Syntax
- – Use Strcpy() Function for Modification
- – Use Memcpy To Copy an Array
- Conclusion
Why Is the “Error: Assignment to Expression With Array Type” Error Happening?
The Program error: assignment to expression with array type error usually happens when you use an array type that is not assignable or is trying to change the constant value in the program. Moreover, you will encounter the same error if the block of memory is below 60 chars.
However, these reasons are not the only ones contributing to the cause of the error. There are a few other reasons behind the occurrence of this error such as
- Not filling the struct with pointers.
- Syntax error
- Directly assigned a value to a string.
- Trying to change the constant.
– Using Un-assignable Array Type
It is a common array-type error the programmers make while coding. They end up accidentally using an unassignable array type that cannot be used by the program and get an expression error.
The array function has unassignable array types, and the programmers forget them and later use that array type; thus, the error occurs. Given below is a program used as an example of an un-assignable array type:
Program:
#define N 20
typedef struct{
char name[I];
char surname[I];
int age;
} data;
int main() {
data s1;
s1.name=”Arora”;
s1.surname = “Rayn”;
s1.age = 18;
getchar();
return 0;
}
The issue is in the program line:
This is because s1.name is an array type which is not assignable. Thus, the output contains an error.
– The Block of Memory Is Below 60 Chars
The error also occurs if the block of memory is below 60 chars. It is a defined fact that the data should be a block of memory that fits 60 chars.
Taking the example used above, “data s1;” allocates the memory on the stack. Assignments just copy numbers or sometimes pointers, and it fails, such as (s1.name = “Arora” ;).
This failure in the program happened because the s1.name is the start of a struct 64 bytes long can be detected by the compiler, and “Arora” is a 6 bytes long char[]. It is six bytes long due to the trailing in the C strings. Therefore, assigning a pointer to a string into a string is impossible, and an expression error occurs.
Here’s an example for better understanding:
Program:
memcpy(s1.surname, “Ryan”, 6);
s1.age = 2;
Output:
The output of this program will not be according to the desired output. It will be something like this:
Error: assignment to expression with an array type.
– Not Filling the Struct With Pointers
If the programmer does not define a struct which points towards char arrays of any length, it will cause an expression error. If the programmer uses a struct field, they have to set pointers in it too.
Here’s an example where the programmer hasn’t defined a struct which points towards a char array.
Program:
char *Ella;
char *Billie;
int age;
} data;
– Syntax Error
Programmers must be careful with the functions they use and if they are using them in the correct order or syntax. This error can also occur if the user has typed in the wrong expression within the syntax.
If that’s the case, then an expression error will occur. Here is an example of the wrong syntax, where using “-” is invalid:
printf( “Name – %sn”, s1.name);
– Directly Assigned a Value to a String
The C programming language does not allow its users to assign the value to a string directly. Thus, directly assigning value to a string is not possible, and if the programmer has done that, they will receive an expression error again.
Here’s an example that shows a directly assigned value to a string:
struct (s1.name, “New_Name”);
– Trying To Change the Constant
Another reason why the programmer gets the error is that they are trying to change a constant value. When a string is initialized, such as “char sample[19];”, the sample itself is a constant pointer. This means the user can change the value of the thing that the pointer is pointing to, but cannot change the value of the pointer itself.
When “char sample” is initialized, it is like the sample in which the pointer is initialized aschar* const, and when the user tries to change the pointer, they are actually trying to change the string’s address.
Moreover, when the user compiles and runs the program, the assigned string fills part of the memory independent of s1.name.
To understand better, try running the following code :
Program:
char name[19];
printf(“address of sample:%d address of a random string:%d”,name,”Arora”);
}
The output will give the programmer two independent addresses. The first address is the address of s1.name and the second is the address of Arora. Therefore, the programmer cannot change s1.name address to Arora address because it is a constant.
In order to fix the “error: assignment to expression with array type” error, it has various specific solutions, such as using the assignable array-type, using the correct syntax and having a block of memory that is not below 60 bytes.
However, multiple other solutions to this error are discussed in detail in this article. They are given below:
– Use Assignable Array Type
Always use the array type that is assignable by the arrays. By using an unassignable array will not be recognized by the program, and an error will occur. To avoid this, make sure the correct array is being used.
To elaborate further, the assignment operator shall have a modifiable lvalue as its left operand. Check out the following example.
Program:
#define N 30
typedef struct{
char name[N];
char surname[N];
int age;
} data;
int main() {
data s1 = {“Arora”, “Rayn”, 20};
getchar();
return 0;
}
– Use Strcpy() To Copy Into the Array
Regarding the modifiable lvalue, a modifiable lvalue is an lvalue that does not have any array type. Therefore, it is said to use strcpy() to copy data into an array. With that said, (data s1 = {“Arora”, “Rayn”, 20};) worked fine because it is not a direct assignment involving assignment operator.
An error occurs when the programmer uses a brace-enclosed initializer list to provide the initial values of the object. Thus, by the law of initialization, each brace-enclosed initializer list should have an associated current object.
If no designations are present, then subobjects of the current object are initialized in order according to the type of the current object. In the above examples, the order is: array elements in increasing subscript order, the structure members in declaration order, and the first named member of a union.
– Block of Memory That Fits 60 Chars
Use the struct function to define a struct which points to char arrays of any length. This way, the user does not have to worry about the length of the block of memory. The length can be below 60 chars, yet the program will run smoothly.
However, if you is not using the struct function, it is important to take care of the char length and that the memory block should fit 60 chars and not below. If it doesn’t fit, the error will occur.
– Fill the Structure With Pointers
As mentioned above, the error will occur if the struct is not filled with a pointer. Therefore, make sure to fill the struct with pointers that point to char arrays.
Do keep in mind that the ints and pointers can have different sizes. Given below is a program for better understanding.
Program:
s1.name = “Arora”;
s1.surname = “Ryan”;
s1.age = 3;
In this example, we have assigned/filled the struct with the pointers.
– Use Correct Syntax
Make sure to use the correct syntax before coding. In case the programmer gets confused about the syntax, do a quick google search on the right syntax and go back to coding error-free.
Given below are the two examples of correct syntax while coding:
printf( “Name : %sn”, s1.name);
– Use Strcpy() Function for Modification
In order to make modifications in the pointer or overall program, make sure to use the strcpy() function. This function is used for modifying the value as well.
It is important to use the strcpy() function to modify value because directly assigning the value to a string is impossible in a C programming language. By using that function, the user can get rid of assignable errors. Given below is an example of how to modify value using strcpy().
strcpy(s1.name, “New_Name”);
– Use Memcpy To Copy an Array
Another method a programmer can use is by using the memcpy function to copy an array into a string. This will save them from errors.
Below are two examples of using the memcpy function to copy an array.
Example#1:
struct Image *ex = calloc(1, sizeof *ex);
ex->name = “tests”;
memcpy(ex->transform, transform, sizeof ex->transform);
Example#2:
The programmer can use the memcpy() function present in the header file. Here’s how:
{
float transform[7] = {0,0,0,0,0,0,0};
struct Image *ex = calloc(1,sizeof(struct Image));
ex->name=”tests”;
memcpy(ex->transform ,transform , sizeof(ex->transform));
free(ex);
return 0;
}
Conclusion
After reading this guide, the reader will have a clear and in-depth understanding of the “error: assignment to expression with array type” error message. This article covers almost all the reasons and solutions for this error. Here are the key points to take notes from:
- Use the correct syntax format and write down the basic, most common syntax used for the program the programmer will use.
- Carefully check the struct() function. The pointers should be filled and pointed to the char array.
- For modifying, changing, and copying an array using either memcpy or strcpy() function.
By following this guide properly, you will be able to master the art of fixing this error.
- Author
- Recent Posts
Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.
C programming is not language programmers are incognizant of. It is a general-purpose language ideally used to develop different software such as databases, operating systems, compilers, and so on. Despite being an old programming language, C is still popular among programmers as it is capable of supporting high-level and low-level language features. It is basically a compiled (C)programming language. Even beginners are trying to learn it by executing various programs. When using C, you may encounter the error “Error: assignment to expression with array type”.
You don’t need to worry or wonder how to get it resolved. We are here to help you solve the error with simple solutions. But first, have a look at how the error message shows up
How the error pops up
When you try to execute a new project, you get into trouble. Let’s take the look at the program code that returns the error message
#include <stdio.h>
#define N 30
typedef struct{
char name[N];
char surname[N];
int age;
} data;
int main() {
data s1;
s1.name="Paolo";
s1.surname = "Rossi";
s1.age = 19;
getchar();
return 0;
}
The code used:
s1.name="Paolo"
s1.surname="Rossi"
data s1 = {"Paolo", "Rossi", 19};
That’s when you get the error message.
"error: assignment to expression with array type error"
Solutions To Fix the Error Message “Error: assignment to expression with array type”
The error shows up because it is not allowed to directly assign a value to a string in C. Have a look at the solutions to tackle the error
Solution 1 – Use strcpy()
To solve the error, you need to modify the value by using strcpy() function. To do that, follow the below code
strcpy(s1.name , "Egzona");
printf( "Name : %sn", s1.name);
Solution 2 – Follow the instruction
You have defined ‘data’ in the code that must be the memory block that should fit 60 chars and 4 int. have a look at the code to see the data
typedef struct{
char name[30];
char surname[30];
int age;
} data;
And this is how it divides:
[----------------------------,------------------------------,----]
^ this is name ^ this is surname ^ this is age
With this, the memory is allocated on the stack. Like this:
It copies the numbers as well as pointers (sometimes).
The following fails
It happens because s1.name is the beginning of the struct, which is 64 bytes long. While ‘Paula’ is a char that is 6 bytes long, it is 6 as it also has a trailing . Hence. It tries to assign a pointer to a string.
In order to copy ‘Rossie’ into the struct at surname and ‘Paula’ at the name, follow the code
memcpy(s1.name, "Paulo", 6);
memcpy(s1.surname, "Rossi", 6);
s1.age = 1;
The result is like this:
[Paulo0----------------------,Rossi0-------------------------,0001]
The strcpy() function works the same way, but it is aware of the termination , which does not require length.
An alternate to fix is to use a struct that can point char array of any specified length.
typedef struct {
char *name;
char *surname;
int age;
} data;
It can create the following
Filling the struct with the help of pointers can make it work.
s1.name = "Paulo";
s1.surname = "Rossi";
s1.age = 1;
It shows this:
The pointers are 4 and 10.
Conclusion
We have discussed the solutions to fix the exception “Error: assignment to expression with array type”. Keeping the solutions and tips in mind when coding or using this post as a reference to solve the error can help. I hope you find it useful!
Формулировка задачи:
Всем доброго времени суток!Я хотел бы у вас узнать в чем заключается проблема:
struct year { char jan[6];// Январь char feb[7];// Февраль char mar[4];// Март char apr[6];// Апрель char may[3];// Май char jun[4];// Июнь char jul[4];// Июль char aug[6];// Август char sep[8];//Сентябрь char oct[7];//Октябрь char nov[6];//Ноябрь char dec[7];//Декабрь }; main() { struct year month; month.jan = "January"; }
У меня выдает ошибку при инициализации переменной jan:
main.c: In function ‘main’:
main.c:26:12: error: assignment to expression with array type
Так как я новичок,я не совсем понимаю как можно решить данную проблему самостоятельно.Надеюсь на ваше понимание и помощь. Заранее благодарен!
И у меня выдает ошибку,даже тогда,когда я использую:
include ... strcopy(month.jan,"January");
Выдает ошибку:
C:Users7349~1AppDataLocalTempcculMbo1.o:main.c.text+0x32): undefined reference to `strcopy’
collect2.exe: error: ld returned 1 exit status
Я почти разобрался проблемой(надо было strcpy) и сразу же появилась другая :
когда я вывожу через printf(«%c»,month.jan), выводится символ «ф».Как исправить данную проблему?
Код к задаче: «Структура, ошибка «assignment to expression with array type»»
textual
#include <stdio.h> #include <stdlib.h> #include <locale.h> #include <string.h> struct year { char jan[10];// Январь char feb[10];// Февраль char mar[10];// Март char apr[10];// Апрель char may[10];// Май char jun[10];// Июнь char jul[10];// Июль char aug[10];// Август char sep[10];//Сентябрь char oct[10];//Октябрь char nov[10];//Ноябрь char dec[10];//Декабрь }; int main() { struct year month; strcpy(month.jan,"January");//для хранения нужно 8 char как минимум printf("%s",month.jan); }
Полезно ли:
8 голосов , оценка 4.000 из 5
#include <stdio.h>
int main(void) {
int arr[10];
arr = "Hello";
printf("%s",arr);
return 0;
}
Приведенный выше код показывает ошибку компилятора:
t.c: In function ‘main’:
t.c:5:9: error: assignment to expression with array type
arr = "Hello";
^
t.c:6:12: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int *’ [-Wformat=]
printf("%s",arr);
^
Тогда как приведенный ниже код работает нормально.
#include <stdio.h>
int main(void) {
char arr[10] = "Hello";
printf("%s",arr);
return 0;
}
Оба выглядят одинаково для меня. Что мне здесь не хватает?
2 ответа
Лучший ответ
Они не идентичны.
Прежде всего, не имеет смысла инициализировать массив int
строковым литералом, а в худшем случае он может вызвать неопределенное поведение, так как указатель на целочисленное преобразование и достоверность преобразованного результата после этого будут сильно зависеть от платформы. В связи с этим оба фрагмента являются недействительными.
Затем, исправляя тип данных, учитывая, что используется char
массив,
-
В первом случае
arr = "Hello";
назначение , которое нельзя использовать с тип массива как LHS присваивания.
-
Ото,
char arr[10] = "Hello";
инициализация , которая является абсолютно допустимым ,
4
Sourav Ghosh
27 Янв 2017 в 08:42
Не знаю, как работает ваш второй код (в моем случае он не работает, ПОЖАЛУЙСТА, СКАЖИТЕ МНЕ, ЧТО МОЖЕТ БЫТЬ ПРИЧИНОЙ), он говорит: array of inappropriate type (int) initialized with string constant
Поскольку вы не можете просто присвоить целую string
переменной integer
. но вы можете назначить одну character
переменной int
, например: int a[5]={'a','b','c','d','d'}
0
akitsme
27 Янв 2017 в 08:36