How to solve “Error: Assignment to expression with array type” in C?

How to solve "Error: Assignment to expression with array type" in C?

In C programming, you might have encountered the “ Error: Assignment to expression with array type “. This error occurs when trying to assign a value to an already initialized  array , which can lead to unexpected behavior and program crashes. In this article, we will explore the root causes of this error and provide examples of how to avoid it in the future. We will also learn the basic concepts involving the array to have a deeper understanding of it in C. Let’s dive in!

What is “Error: Assignment to expression with array type”? What is the cause of it?

An array is a collection of elements of the same data type that are stored in contiguous memory locations. Each element in an array is accessed using an index number. However, when trying to assign a value to an entire array or attempting to assign an array to another array, you may encounter the “Error: Assignment to expression with array type”. This error occurs because arrays in C are not assignable types, meaning you cannot assign a value to an entire array using the assignment operator.

First example: String

Here is an example that may trigger the error:

In this example, we have declared a char array “name” of size 10 and initialized it with the string “John”. Then, we are trying to assign a new string “Mary” to the entire array. However, this is not allowed in C because arrays are not assignable types. As a result, the compiler will throw the “Error: Assignment to expression with array type”.

Initialization

When you declare a char array in C, you can initialize it with a string literal or by specifying each character separately. In our example, we initialized the char array “name” with the string literal “John” as follows:

This creates a char array of size 10 and initializes the first four elements with the characters ‘J’, ‘o’, ‘h’, and ‘n’, followed by a null terminator ‘\0’. It’s important to note that initializing the array in this way does not cause the “Error: Assignment to expression with array type”.

On the other hand, if you declare a char array without initializing it, you will need to assign values to each element of the array separately before you can use it. Failure to do so may lead to undefined behavior. Considering the following code snippet:

We declared a char array “name” of size 10 without initializing it. Then, we attempted to assign a new string “Mary” to the entire array, which will result in the error we are currently facing.

When you declare a char array in C, you need to specify its size. The size determines the maximum number of characters the array can hold. In our example, we declared the char array “name” with a fixed size of 10, which can hold up to 9 characters plus a null terminator ‘\0’.

If you declare a char array without specifying its size, the compiler will automatically determine the size based on the number of characters in the string literal you use to initialize it. For instance:

This code creates a char array “name” with a size of 5, which is the number of characters in the string literal “John” plus a null terminator. It’s important to note that if you assign a string that is longer than the size of the array, you may encounter a buffer overflow.

Second example: Struct

We have known, from the first example, what is the cause of the error with string, after that, we dived into the definition of string, its properties, and the method on how to initialize it properly. Now, we can look at a more complex structure:

This struct “struct_type” contains an integer variable “id” and a character array variable “string” with a fixed size of 10. Now let’s create an instance of this struct and try to assign a value to the “string” variable as follows:

As expected, this will result in the same “Error: Assignment to expression with array type” that we encountered in the previous example. If we compare them together:

  • The similarity between the two examples is that both involve assigning a value to an initialized array, which is not allowed in C.
  • The main difference between the two examples is the scope and type of the variable being assigned. In the first example, we were dealing with a standalone char array, while in the second example, we are dealing with a char array that is a member of a struct. This means that we need to access the “string” variable through the struct “s1”.

So basically, different context, but the same problem. But before dealing with the big problem, we should learn, for this context, how to initialize a struct first. About methods, we can either declare and initialize a new struct variable in one line or initialize the members of an existing struct variable separately.

Take the example from before, to declare and initialize a new struct variable in one line, use the following syntax:

To initialize the members of an existing struct variable separately, you can do like this:

Both of these methods will initialize the “id” member to 1 and the “struct_name” member to “structname”. The first one is using a brace-enclosed initializer list to provide the initial values of the object, following the law of initialization. The second one is specifically using strcpy() function, which will be mentioned in the next section.

How to solve “Error: Assignment to expression with array type”?

Initialize the array type member during the declaration.

As we saw in the first examples, one way to avoid this error is to initialize the array type member during declaration. For example:

This approach works well if we know the value of the array type member at the time of declaration. This is also the basic method.

Use the strcpy() function

We have seen the use of this in the second example. Another way is to use the strcpy() function to copy a string to the array type member. For example:

Remember to add the string.h library to use the strcpy() function. I recommend going for this approach if we don’t know the value of the array type member at the time of declaration or if we need to copy a string to the member dynamically during runtime. Consider using strncpy() instead if you are not sure whether the destination string is large enough to hold the entire source string plus the null character.

Use pointers

We can also use pointers to avoid this error. Instead of assigning a value to the array type member, we can assign a pointer to the member and use malloc() to dynamically allocate memory for the member. Like the example below:

Before using malloc(), the stdlib.h library needs to be added. This approach is also working well for the struct type. In the next approach, we will talk about an ‘upgrade-version’ of this solution.

Use structures with flexible array members (FAMs)

If we are working with variable-length arrays, we can use structures with FAMs to avoid this error. FAMs allow us to declare an array type member without specifying its size, and then allocate memory for the member dynamically during runtime. For example:

The code is really easy to follow. It is a combination of the struct defined in the second example, and the use of pointers as the third solution. The only thing you need to pay attention to is the size of memory allocation to “s”. Because we didn’t specify the size of the “string” array, so at the allocating memory process, the specific size of the array(10) will need to be added.

This a small insight for anyone interested in this example. As many people know, the “sizeof” operator in C returns the size of the operand in bytes. So when calculating the size of the structure that it points to, we usually use sizeof(*), or in this case: sizeof(*s).

But what happens when the structure contains a flexible array member like in our example? Assume that sizeof(int) is 4 and sizeof(char) is 1, the output will be 4. You might think that sizeof(*s) would give the total size of the structure, including the flexible array member, but not exactly. While sizeof is expected to compute the size of its operand at runtime, it is actually a compile-time operator. So, when the compiler sees sizeof(*s), it only considers the fixed-size members of the structure and ignores the flexible array member. That’s why in our example, sizeof(*s) returns 4 and not 14.

How to avoid “Error: Assignment to expression with array type”?

Summarizing all the things we have discussed before, there are a few things you can do to avoid this error:

  • Make sure you understand the basics of arrays, strings, and structures in C.
  • Always initialize arrays and structures properly.
  • Be careful when assigning values to arrays and structures.
  • Consider using pointers instead of arrays in certain cases.

The “ Error: Assignment to expression with array type ” in C occurs when trying to assign a value to an already initialized  array . This error can also occur when attempting to assign a value to an array within a  struct . To avoid this error, we need to initialize arrays with a specific size, use the strcpy() function when copying strings, and properly initialize arrays within structures. Make sure to review the article many times to guarantee that you can understand the underlying concepts. That way you will be able to write more efficient and effective code in C. Have fun coding!

“Expected unqualified-id” error in C++ [Solved]

How to Solve does not name a type error in C++

Next: Unions , Previous: Overlaying Structures , Up: Structures   [ Contents ][ Index ]

15.13 Structure Assignment

Assignment operating on a structure type copies the structure. The left and right operands must have the same type. Here is an example:

Notionally, assignment on a structure type works by copying each of the fields. Thus, if any of the fields has the const qualifier, that structure type does not allow assignment:

See Assignment Expressions .

When a structure type has a field which is an array, as here,

structure assigment such as r1 = r2 copies array fields’ contents just as it copies all the other fields.

This is the only way in C that you can operate on the whole contents of a array with one operation: when the array is contained in a struct . You can’t copy the contents of the data field as an array, because

would convert the array objects (as always) to pointers to the zeroth elements of the arrays (of type struct record * ), and the assignment would be invalid because the left operand is not an lvalue.

Troubleshooting 'Error: Assignment to Expression with Array Type': Tips and Solutions for Resolving Array Assignment Issues

David Henegar

If you are a developer, you might have come across the error message "Error: Assignment to Expression with Array Type". This error is related to array assignment issues and can be frustrating to resolve. In this guide, we will provide valuable and relevant information to help you troubleshoot and resolve this error.

Understanding the Error Message

Before we dive into the solutions, let's first understand what the error message means. This error occurs when you try to assign a value to an array. Here is an example:

In the above example, the error message "Error: Assignment to Expression with Array Type" will be displayed because you are trying to assign a value to an array.

Tips for Resolving Array Assignment Issues

Here are some tips to help you resolve array assignment issues:

1. Use a loop to assign values to an array

One way to assign values to an array is by using a loop. Here is an example:

In the above example, we used a loop to assign values to the arr array.

2. Use the memcpy function to copy values from one array to another

You can use the memcpy function to copy values from one array to another. Here is an example:

In the above example, we used the memcpy function to copy the values from arr1 to arr2 .

3. Use the std::copy function to copy values from one array to another

You can also use the std::copy function to copy values from one array to another. Here is an example:

In the above example, we used the std::copy function to copy the values from arr1 to arr2 .

Q1. What is an array in C++?

An array is a collection of similar data types that are stored in contiguous memory locations.

Q2. What is the syntax for declaring an array in C++?

The syntax for declaring an array in C++ is as follows:

Q3. What is the difference between an array and a pointer in C++?

An array is a collection of similar data types that are stored in contiguous memory locations, whereas a pointer is a variable that stores the memory address of another variable.

Q4. What is the difference between an array and a vector in C++?

An array is a fixed-size collection of similar data types that are stored in contiguous memory locations, whereas a vector is a dynamic-size collection of similar data types that are stored in non-contiguous memory locations.

Q5. What is the difference between an array and a list in C++?

An array is a collection of similar data types that are stored in contiguous memory locations, whereas a list is a collection of similar data types that are stored in non-contiguous memory locations.

In this guide, we provided valuable and relevant information to help you troubleshoot and resolve the "Error: Assignment to Expression with Array Type" error. By following the tips and solutions we provided, you can easily fix array assignment issues and improve your programming skills.

Related Links

  • C++ Pointers
  • C++ Vectors

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to Lxadm.com.

Your link has expired.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.

C Programming Tutorial

  • Array of Structures in C

Last updated on July 27, 2020

Declaring an array of structure is same as declaring an array of fundamental types. Since an array is a collection of elements of the same type. In an array of structures, each element of an array is of the structure type.

Let's take an example:

struct car { char make[20]; char model[30]; int year; };

Here is how we can declare an array of structure car .

assignment to expression with array type struct

Here arr_car is an array of 10 elements where each element is of type struct car . We can use arr_car to store 10 structure variables of type struct car . To access individual elements we will use subscript notation ( [] ) and to access the members of each element we will use dot ( . ) operator as usual.

arr_stu[0] : points to the 0th element of the array. arr_stu[1] : points to the 1st element of the array.

and so on. Similarly,

arr_stu[0].name : refers to the name member of the 0th element of the array. arr_stu[0].roll_no : refers to the roll_no member of the 0th element of the array. arr_stu[0].marks : refers to the marks member of the 0th element of the array.

Recall that the precedence of [] array subscript and dot( . ) operator is same and they evaluates from left to right. Therefore in the above expression first array subscript( [] ) is applied followed by dot ( . ) operator. The array subscript ( [] ) and dot( . ) operator is same and they evaluates from left to right. Therefore in the above expression first [] array subscript is applied followed by dot ( . ) operator.

Let's rewrite the program we used in the last chapter as an introduction to structures.

#include<stdio.h> #include<string.h> #define MAX 2 struct student { char name[20]; int roll_no; float marks; }; int main() { struct student arr_student[MAX]; int i; for(i = 0; i < MAX; i++ ) { printf("\nEnter details of student %d\n\n", i+1); printf("Enter name: "); scanf("%s", arr_student[i].name); printf("Enter roll no: "); scanf("%d", &arr_student[i].roll_no); printf("Enter marks: "); scanf("%f", &arr_student[i].marks); } printf("\n"); printf("Name\tRoll no\tMarks\n"); for(i = 0; i < MAX; i++ ) { printf("%s\t%d\t%.2f\n", arr_student[i].name, arr_student[i].roll_no, arr_student[i].marks); } // signal to operating system program ran fine return 0; }

Expected Output:

Enter details of student 1 Enter name: Jim Enter roll no: 1 Enter marks: 44 Enter details of student 2 Enter name: Tim Enter roll no: 2 Enter marks: 76 Name Roll no Marks Jim 1 44.00 Tim 2 76.00

How it works:

In lines 5-10, we have declared a structure called the student .

In line 14, we have declared an array of structures of type struct student whose size is controlled by symbolic constant MAX . If you want to increase/decrease the size of the array just change the value of the symbolic constant and our program will adapt to the new size.

In line 17-29, the first for loop is used to enter the details of the student.

In line 36-40, the second for loop prints all the details of the student in tabular form.

Initializing Array of Structures #

We can also initialize the array of structures using the same syntax as that for initializing arrays. Let's take an example:

struct car { char make[20]; char model[30]; int year; }; struct car arr_car[2] = { {"Audi", "TT", 2016}, {"Bentley", "Azure", 2002} };

Load Comments

  • Intro to C Programming
  • Installing Code Blocks
  • Creating and Running The First C Program
  • Basic Elements of a C Program
  • Keywords and Identifiers
  • Data Types in C
  • Constants in C
  • Variables in C
  • Input and Output in C
  • Formatted Input and Output in C
  • Arithmetic Operators in C
  • Operator Precedence and Associativity in C
  • Assignment Operator in C
  • Increment and Decrement Operators in C
  • Relational Operators in C
  • Logical Operators in C
  • Conditional Operator, Comma operator and sizeof() operator in C
  • Implicit Type Conversion in C
  • Explicit Type Conversion in C
  • if-else statements in C
  • The while loop in C
  • The do while loop in C
  • The for loop in C
  • The Infinite Loop in C
  • The break and continue statement in C
  • The Switch statement in C
  • Function basics in C
  • The return statement in C
  • Actual and Formal arguments in C
  • Local, Global and Static variables in C
  • Recursive Function in C
  • One dimensional Array in C
  • One Dimensional Array and Function in C
  • Two Dimensional Array in C
  • Pointer Basics in C
  • Pointer Arithmetic in C
  • Pointers and 1-D arrays
  • Pointers and 2-D arrays
  • Call by Value and Call by Reference in C
  • Returning more than one value from function in C
  • Returning a Pointer from a Function in C
  • Passing 1-D Array to a Function in C
  • Passing 2-D Array to a Function in C
  • Array of Pointers in C
  • Void Pointers in C
  • The malloc() Function in C
  • The calloc() Function in C
  • The realloc() Function in C
  • String Basics in C
  • The strlen() Function in C
  • The strcmp() Function in C
  • The strcpy() Function in C
  • The strcat() Function in C
  • Character Array and Character Pointer in C
  • Array of Strings in C
  • Array of Pointers to Strings in C
  • The sprintf() Function in C
  • The sscanf() Function in C
  • Structure Basics in C
  • Array as Member of Structure in C
  • Nested Structures in C
  • Pointer to a Structure in C
  • Pointers as Structure Member in C
  • Structures and Functions in C
  • Union Basics in C
  • typedef statement in C
  • Basics of File Handling in C
  • fputc() Function in C
  • fgetc() Function in C
  • fputs() Function in C
  • fgets() Function in C
  • fprintf() Function in C
  • fscanf() Function in C
  • fwrite() Function in C
  • fread() Function in C

Recent Posts

  • Machine Learning Experts You Should Be Following Online
  • 4 Ways to Prepare for the AP Computer Science A Exam
  • Finance Assignment Online Help for the Busy and Tired Students: Get Help from Experts
  • Top 9 Machine Learning Algorithms for Data Scientists
  • Data Science Learning Path or Steps to become a data scientist Final
  • Enable Edit Button in Shutter In Linux Mint 19 and Ubuntu 18.04
  • Python 3 time module
  • Pygments Tutorial
  • How to use Virtualenv?
  • Installing MySQL (Windows, Linux and Mac)
  • What is if __name__ == '__main__' in Python ?
  • Installing GoAccess (A Real-time web log analyzer)
  • Installing Isso

Intro to C for CS31 Students

Part 2: structs & pointers.

  • Pointers and Functions C style "pass by referece"
  • Dynamic Memory Allocation (malloc and free)
  • Pointers to Structs

Defining a struct type

Declaring variables of struct types, accessing field values, passing structs to functions, rules for using pointer variables.

  • Next, initialize the pointer variable (make it point to something). Pointer variables store addresses . Initialize a pointer to the address of a storage location of the type to which it points. One way to do this is to use the ampersand operator on regular variable to get its address value: int x; char ch; ptr = &x; // ptr get the address of x, pointer "points to" x ------------ ------ ptr | addr of x|--------->| ?? | x ------------ ------ cptr = &ch; // ptr get the address of ch, pointer "points to" ch cptr = &x; // ERROR! cptr can hold a char address only (it's NOT a pointer to an int) All pointer variable can be set to a special value NULL . NULL is not a valid address but it is useful for testing a pointer variable to see if it points to a valid memory address before we access what it points to: ptr = NULL; ------ ------ cptr = NULL; ptr | NULL |-----| cptr | NULL |----| ------ ------
  • Use *var_name to dereference the pointer to access the value in the location that it points to. Some examples: int *ptr1, *ptr2, x, y; x = 8; ptr1 = NULL; ptr2 = &x; ------------ ------ ptr2 | addr of x|--------->| 8 | x ------------ ------ *ptr2 = 10; // dereference ptr2: "what ptr2 points to gets 10" ------------ ----- ptr2 | addr of x|--------->| 10 | x ------------ ----- y = *ptr2 + 3; // dereference ptr2: "y gets what ptr2 points to plus 3" ----- ----- ptr1 = ptr2; // ptr1 gets address value stored in ptr2 ------------ ----- ptr2 | addr of x |--------->| 10 | x ------------ ----- /\ ------------ | ptr1 | addr of x |-------------- ------------ // TODO: finish tracing through this code and show what is printed *ptr1 = 100; ptr1 = &y; *ptr1 = 80; printf("x = %d y = %d\n", x, y); printf("x = %d y = %d\n", *ptr2, *ptr1);
  • and what does this mean with respect to the value of each argument after the call?
  • Implement a program with a swap function that swaps the values stored in its two arguments. Make some calls to it in main to test it out.

malloc and free

Pointers, the heap, and functions, linked lists in c.

cppreference.com

Struct declaration.

(C11)
Miscellaneous
(C11)
(C23)

A struct is a type consisting of a sequence of members whose storage is allocated in an ordered sequence (as opposed to union, which is a type consisting of a sequence of members whose storage overlaps).

The type specifier for a struct is identical to the union type specifier except for the keyword used:

Syntax Explanation Forward declaration Keywords Notes Example Defect reports References See also

[ edit ] Syntax

attr-spec-seq (optional) name (optional) struct-declaration-list (1)
attr-spec-seq (optional) name (2)
name - the name of the struct that's being defined
struct-declaration-list - any number of variable declarations, declarations, and declarations. Members of incomplete type and members of function type are not allowed (except for the flexible array member described below)
attr-spec-seq - (C23)optional list of , applied to the struct type

[ edit ] Explanation

Within a struct object, addresses of its elements (and the addresses of the bit-field allocation units) increase in order in which the members were defined. A pointer to a struct can be cast to a pointer to its first member (or, if the member is a bit-field, to its allocation unit). Likewise, a pointer to the first member of a struct can be cast to a pointer to the enclosing struct. There may be unnamed padding between any two members of a struct or after the last member, but not before the first member. The size of a struct is at least as large as the sum of the sizes of its members.

If a struct defines at least one named member, it is allowed to additionally declare its last member with incomplete array type. When an element of the flexible array member is accessed (in an expression that uses operator or with the flexible array member's name as the right-hand-side operand), then the struct behaves as if the array member had the longest size fitting in the memory allocated for this object. If no additional storage was allocated, it behaves as if an array with 1 element, except that the behavior is undefined if that element is accessed or a pointer one past that element is produced. Initialization and the assignment operator ignore the flexible array member. sizeof omits it, but may have more trailing padding than the omission would imply. Structures with flexible array members (or unions who have a recursive-possibly structure member with flexible array member) cannot appear as array elements or as members of other structures.

s { int n; double d[]; }; // s.d is a flexible array member   struct s t1 = { 0 }; // OK, d is as if double d[1], but UB to access struct s t2 = { 1, { 4.2 } }; // error: initialization ignores flexible array   // if sizeof (double) == 8 struct s *s1 = (sizeof (struct s) + 64); // as if d was double d[8] struct s *s2 = (sizeof (struct s) + 40); // as if d was double d[5]   s1 = (sizeof (struct s) + 10); // now as if d was double d[1]. Two bytes excess. double *dp = &(s1->d[0]); // OK *dp = 42; // OK s1->d[1]++; // Undefined behavior. 2 excess bytes can't be accessed // as double.   s2 = (sizeof (struct s) + 6); // same, but UB to access because 2 bytes are // missing to complete 1 double dp = &(s2->d[0]); // OK, can take address just fine *dp = 42; // undefined behavior   *s1 = *s2; // only copies s.n, not any element of s.d // except those caught in sizeof (struct s)
(since C99)

Similar to union, an unnamed member of a struct whose type is a struct without name is known as . Every member of an anonymous struct is considered to be a member of the enclosing struct or union, keeping their structure layout. This applies recursively if the enclosing struct or union is also anonymous.

v { union // anonymous union { struct { int i, j; }; // anonymous structure struct { long k, l; } w; }; int m; } v1;   v1.i = 2; // valid v1.k = 3; // invalid: inner structure is not anonymous v1.w.k = 5; // valid

Similar to union, the behavior of the program is undefined if struct is defined without any named members (including those obtained via anonymous nested structs or unions).

(since C11)

[ edit ] Forward declaration

A declaration of the following form

attr-spec-seq (optional) name

hides any previously declared meaning for the name name in the tag name space and declares name as a new struct name in current scope, which will be defined later. Until the definition appears, this struct name has incomplete type .

This allows structs that refer to each other:

Note that a new struct name may also be introduced just by using a struct tag within another declaration, but if a previously declared struct with the same name exists in the tag name space , the tag would refer to that name

[ edit ] Keywords

[ edit ] notes.

See struct initialization for the rules regarding the initializers for structs.

Because members of incomplete type are not allowed, and a struct type is not complete until the end of the definition, a struct cannot have a member of its own type. A pointer to its own type is allowed, and is commonly used to implement nodes in linked lists or trees.

Because a struct declaration does not establish scope , nested types, enumerations and enumerators introduced by declarations within struct-declaration-list are visible in the surrounding scope where the struct is defined.

[ edit ] Example

Possible output:

[ edit ] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C standards.

DR Applied to Behavior as published Correct behavior
C11 members of anonymous structs/unions were considered members of the enclosing struct/union they retain their memory layout

[ edit ] References

  • C23 standard (ISO/IEC 9899:2024):
  • 6.7.2.1 Structure and union specifiers (p: TBD)
  • C17 standard (ISO/IEC 9899:2018):
  • 6.7.2.1 Structure and union specifiers (p: 81-84)
  • C11 standard (ISO/IEC 9899:2011):
  • 6.7.2.1 Structure and union specifiers (p: 112-117)
  • C99 standard (ISO/IEC 9899:1999):
  • 6.7.2.1 Structure and union specifiers (p: 101-104)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 3.5.2.1 Structure and union specifiers

[ edit ] See also

  • struct and union member access
  • struct initialization
for Class declaration
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 6 January 2024, at 23:45.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Assignment to Expression With Array Type

Tuesday, December 12, 2017

Learning from Error : assignment to expression with array type.

Error Learning : assignment to expression with array type

**error1 : assignment to expression with array type (line 13, line 29)**.

Reason : You cannot directly assign to an array.

Solution : You need to use strcpy() to copy into the array.

What is LHS and RHS? Address1 is on the left hand side (LHS), and “Address2” is on the right hand side (RHS).

Difference between assignment and initialization.

雖然看似沒有不同,但實際compiler轉譯到assembler language是代表不同的assembly code。如果使用在陣列上,那麼用第二個方法就會出現錯誤(直接assign到在LHS的array變數就會出錯),必須使用 strcpy() (使用 strcpy() 需引入標頭檔 #include<string.h> )

除了array以外, struct 結構型態、 const 常數修飾子,都不能這樣使用

<Error example 1> array

  • char name[] = "Sophie"; // is valid
  • char name[]; name[]= "Sophie"; // is not valid

<Error example 2> struct

struct classmate student1 = {.name ="Jack", .no ="34567"}; // valid

<Error example 3> const

  • const int a = 5; // is valid
  • const int a; a = 5; // is not valid

assignment to expression with array type struct

Solution Code:

stack overflow assignment and initialization

← Print right triangle and diamond in C.

→ Sainkho Namtchylak

©2020 Notepadium.

Powered by Hugo and the Notepadium

Can't access an array-type member of a structure?

As a part of learning/exercise process, I attemptd to assign a string to an array-type member of a structure using dot (.) operator of the following sketch; but, the relevant line is not compiled. Would appreciate to know the reason which is not clear to me from the error message.

The problem has nothing to do with the struct. You cannot change an array in the way that you tried. Use this instead

@UKHeliBob Your code of Post-2 works well.

Then, why does the following assignment instruction work when accessing an item of the name[ ] array?

Because you are then only accessing a single item in the array, whereas in your code you are trying to access the whole array at once

As I said, the fact that the array is in a struct is not relevant

In the following codes, I can access the whole array and also an item of the array.

The concern to me is that -- while the following code works:

Then the under-mentioned code should work (logically)?

The struct is irrelevant in this context - you can't assign a C string like that.

C-style arrays have weird quirks, they don't obey the usual value semantics of the language.

To get value semantics, either use a C++ array ( std::array ), or wrap it in a struct:

Otherwise you'll have to use memcpy or strcpy or some equivalent element-by-element copy function.

Edit : unfortunately, the example triggers a bug in previous versions of GCC: c++ - Initializing std::array<char,x> member in constructor using string literal. GCC bug? - Stack Overflow It works fine in Clang and MSVC and the latest version of GCC, though.

As AWOL and I have said, the struct is irrelevant

as an example of what you can do, but they are not equivalent because date is not an array, it is a single int whereas name is an array

Given an array of chars

then you simply can't do

Interestingly, the following codes work though they don't meet my demand:

Another equivalent way using structure pointer.

That's an initialisation, not an assignment.

1. Variable declaration:

2. Variable creation:

3. Variable initialization: I think that it is same as Step-2.

4. Variable assigment: I think that it is same as Step-2 as there is an assignment operator.

Would be glad to know your definitions with examples.

Could you please correct the misleading comments in the code snippets in points 1 and 2?

https://www.google.com/search?q=c%2B%2B+define+declare+initialize

brings you there:

https://stackoverflow.com/questions/23345554/the-differences-between-initialize-define-declare-a-variable

:sweat_smile:

if you use pointers, that seems to be perfectly doable (though not sure how 'safe' that is!)

I assume that you ignored the compiler output such as

:stuck_out_tongue:

This is what I know from literature that "memory space is not allocated" when a variable is declared and not defined. Variable creation refers to assigning a value to it and this is the time when memory space is allocated for that variable/identifier.

Well, my definition would be irrelevant, the standard is the only authority when it comes to these things.

First off, declarations can be definitions. If you really want the details, read [basic.def] in the C++ standard. I'll quote the highlights:

A declaration may introduce one or more names into a translation unit or redeclare names introduced by previous declarations. If so, the declaration specifies the interpretation and semantic properties of these names.
A declaration is said to be a definition of each entity that it defines. [Example 1: the following are definitions int a; // defines a int f(int x) { return x+a; } // defines f and defines x whereas these are just declarations extern int a; // declares a int f(int); // declares f — end example]

Assignment is pretty straightforward [expr.ass] :

In simple assignment (=), the object referred to by the left operand is modified by replacing its value with the result of the right operand. If the right operand is an expression, it is implicitly converted to the cv-unqualified type of the left operand.

Initialization is much more complicated, so I'll refer you to [dcl.init] and give some examples:

What does that mean? What literature? All variable declarations have a corresponding definition somewhere, so it doesn't make a whole lot of sense to say that declaration does not cause allocation.

"Variable creation" is not a term that I am familiar with.

Using C-style casts to make warnings go away is a terrible idea. See https://en.cppreference.com/w/cpp/language/explicit_cast :

When the C-style cast expression is encountered, the compiler attempts to interpret it as the following cast expressions, in this order: a) const_cast< new-type >( expression ) ; b) static_cast< new-type >( expression ) , with extensions: pointer or reference to a derived class is additionally allowed to be cast to pointer or reference to unambiguous base class (and vice versa) even if the base class is inaccessible (that is, this cast ignores the private inheritance specifier). Same applies to casting pointer to member to pointer to member of unambiguous non-virtual base; c) static_cast (with extensions) followed by const_cast; d) reinterpret_cast< new-type >( expression ) ; e) reinterpret_cast followed by const_cast. The first choice that satisfies the requirements of the respective cast operator is selected, even if it cannot be compiled (see example).

In other words: it can perform pretty much any nonsensical cast you can imagine, without any type checking by the compiler. The resulting reinterpret_cast is almost always invalid, see reinterpret_cast conversion - cppreference.com . A C-style cast can also cast away const , which is what you're doing here, which is a recipe for disaster, because now the compiler can no longer check whether the variables that you're writing to are actually writable (which would be undefined behavior).

In short, avoid the use of C-style casts , especially for pointers, and never use it to quickly work around a compiler error or warning .

The correct solution in this case is to use an immutable pointer (which is the right thing to do to point to immutable string literals):

If you absolutely must store a string literal in a non-const pointer, use an explicit const_cast<char *>("lit") , then the readers of your code can at least see that you're doing something fishy. If you then later use that pointer to write to the string literal (with absolutely no way for the compiler to check), it's your own fault when things come crashing down at runtime.

Then why does the "Introduction to C Programming" chapter of a textbook say -- A declared variable in a program is defined either by the user or by the program.

In the following program, I have declared a variable (unsigned int x;) which has been defined (value assignment) by the program (code).

Related Topics

Topic Replies Views Activity
Programming Questions 7 7188 May 6, 2021
Programming Questions 17 193 May 31, 2024
Programming Questions 14 4333 May 6, 2021
Programming Questions 5 486 May 6, 2021
Programming Questions 9 2067 May 5, 2021

Next: Unions , Previous: Overlaying Different Structures , Up: Structures   [ Contents ][ Index ]

15.13 Structure Assignment

Assignment operating on a structure type copies the structure. The left and right operands must have the same type. Here is an example:

Notionally, assignment on a structure type works by copying each of the fields. Thus, if any of the fields has the const qualifier, that structure type does not allow assignment:

See Assignment Expressions .

When a structure type has a field which is an array, as here,

structure assigment such as r1 = r2 copies array fields’ contents just as it copies all the other fields.

This is the only way in C that you can operate on the whole contents of a array with one operation: when the array is contained in a struct . You can’t copy the contents of the data field as an array, because

would convert the array objects (as always) to pointers to the zeroth elements of the arrays (of type struct record * ), and the assignment would be invalid because the left operand is not an lvalue.

assignment to expression with array type struct

C Programming: error: assignment to expression with array type

Hello I am a beginner in C and I was working with structures when i have this problem:

With this one I have this error ( error: assignment to expression with array type ). error: assignment to expression with array type )。--> So I decided to do it using pointers and it actually working this is the code I used:

So the question is what is the difference between both of them since strings are pointers. thank you..

solution1  1  2020-05-15 20:28:31

First part, you try to copy two array of character (string is not a pointer, it is array of character that is terminated by null character \0 ). \0 终止的字符数组)。-->

If you want to copy value of an array to another, you can use memcpy , but for string, you can also use strcpy . memcpy ,但对于字符串,你也可以使用 strcpy 。-->

Second part, you make the pointer point to string literal. The pointer points to first character of the string ( r in this case). r )。-->

You can see How to copy a string using a pointer 如何使用指针复制字符串 -->

And Assigning strings to pointer in C Language 字符串分配给 C 语言中的指针 -->

solution2  1 ACCPTED  2020-05-15 20:30:35

Strings are not pointers, they are sequences of characters terminated with a null byte. These sequences are stored in arrays, which are not pointers either, but objects that live in memory and to which a pointer can point. A pointer is a variable that contains the address of an object in memory.

In the first example, you try and store a string into an array with = . = 将字符串存储到数组中。--> C does not support this type of assignment and complains with an explicit error message. You can copy the string into the array with strcpy , assuming the destination array is large enough to store the bytes of the string, including the null terminator. strcpy 将字符串复制到数组中,假设目标数组足够大以存储字符串的字节,包括 null 终止符。--> "reda" uses 5 bytes, so it is OK to copy it into E[0].nom : "reda" 使用 5 个字节,因此可以将其复制到 E[0].nom :-->

The second example uses a different approach: nom is now defined as a pointer to char . nom 现在定义为指向 char 的指针。--> Defining the array E in main leaves it uninitialized, so you can only read from the pointers after you set their value to point to actual arrays of char somewhere in memory. E[0].nom = "reda"; main 中定义数组 E 使其未初始化,因此您只能在将指针的值设置为指向 memory 中某处的 char 的实际 arrays 后才能读取指针 E[0].nom = "reda"; --> does just that: set the address of the string literal "reda" into the member nom of E[0] . "reda" 的地址设置为 E[0] 的成员 nom 。--> The string literal will be placed by the compiler into an array of its own, including a null terminator, and that must not be changed by the program.

solution3  1  2020-05-15 21:04:32

It is a lower-level concept actually.

If we say char nom[20] than its memory location will be decided at compile time and it will use stack memory (see the difference between stack memory and heap memory to gain more grasp on lover level programming). char nom[20] ,那么它的 memory 位置将在编译时确定,它将使用堆栈 memory(请参阅堆栈 memory 和堆 memory 之间的区别,以更好地掌握情人级编程)。--> so we need to use it with indexes.

On the other hand if we create a string using the double quotes method (or the second way in which you used pointers). The double quoted strings are identified as const char* by the compiler and the string is placed at the heap memory rather than the stack memory. moreover their memory location is not decided at compile time. const char* 并且字符串被放置在堆 memory 而不是堆栈 memory。此外,它们的 memory 位置在编译时没有确定。-->

a very efficient way of testing the difference between these two types of strings is that when you use sizeof() with char[20] nom it will return 20 * sizeof(char) which evaluates to 20 without any doubt. sizeof() 与 char[20] nom 一起使用时,它将毫无疑问地返回 20 * sizeof(char) ,其计算结果为 20 。--> it clearly states that whether you use only 5 characters or 2 characters it will always occupy space of 20 charaters (in stack memory)

but in case of const char* if you use sizeof operator on this variable than it will return the size of the pointer variable which depends on the hardware (32bit will have 4bytes pointer) and (64bit will have 8bytes pointer). const char* 的情况下,如果您在此变量上使用 sizeof 运算符,它将返回指针变量的大小,这取决于硬件(32 位将有 4 字节指针)和(64 位将有 8 字节指针)。--> So, the sizeof operator do not shows how many characters are stored in the pointer. it just shows the size of pointer. but the benefit of using const char* is that only take memory that is required if 4 characters are stored than it will consume 5 byte memory (last byte is additionally added in case of strings) and in case of 8 characters it will consume 9 bytes and so on but note that the characters will be stored in heap(memory) const char* 的好处是,如果存储 4 个字符,则只需要 memory,而不是消耗 5 个字节 memory(最后一个字节在字符串的情况下额外添加),如果是 8 个字符,它将消耗 9 个字节等等,但请注意字符将存储在堆(内存)中-->

What you have been doing in the first problem is that you were assigning a string that is only stored on heap to a data types that is only stored on stack. it is not the matter of string. it the matter of memory model

I hope you might have understood. I not i can elaborate more in comments.

an additional information. Stack Memory is faster compared to the Heap Memory.

  • Related Question
  • Related Blog
  • Related Tutorials

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:[email protected].

  • variable-assignment
  • compiler-errors
  • string-literals
  • linked-list
  • compilation
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Assign to array in struct in c

I have the following code:

It's working OK, but I want to change the initalization of the mem array to be in that way:

But the gcc giving me this error:

error: expected expression before '{' token test->mem = {1,2,3,4,5,6}; With arrow pointing to the left open braces.

What it can be?

EDIT: I also try this code:

And I'm getting this error from gcc:

error: incompatible types when assigning to type 'long int[1048576]' from type 'long int *' test->mem = mem;

I'm not allow to use any C functions.

Nir's user avatar

2 Answers 2

The syntax something = { initial values } is allowed only in initializations , where an object is defined, such as:

An expression such as x = value is an assignment and cannot use the syntax for initializations.

One alternative is to create a temporary object, which you initialize, and then copy the contents of that temporary object into the target:

Regarding the edit to the question:

Arrays may not be assigned; x = value is not valid if x is an array. However, structures may be assigned, so another alternative is to create a structure as a temporary object, initialize it, and assign it:

Note, however, that this code does something the prior code does not. The prior example I showed merely copies six elements into the array. This code creates a temporary object of type Test , which contains 1000 elements, most of them zero, and it copies all of those elements into *test . Even if the compiler optimizes this and uses some code to clear *test rather than actually copying zeroes stored in memory, it takes longer than just copying six elements. So, if you just want a few elements initialized and do not care about the rest, use the former code. If you want all the elements initialized (most to zero), you can use the latter code. (Even so, I would consider alternatives, like using calloc instead of malloc .)

Eric Postpischil's user avatar

Arrays are not pointers (but arrays decay to pointers, see this ), and you cannot assign arrays (only initialize them, or assign struct -s containing them). You could copy the array, e.g.

BTW, you could copy without using memcpy by coding your loop for (int i=0; i<6; i++) test->mem[i] = arr[i]; ....

This leaves 9994 integers in test uninitialized; you might want to clear them:

or use another for loop.

You could also define your initialized structure, e.g.

then assign it, e.g.

but you cannot assign arrays! Even

won't compile.

FWIW, C++11 has std::array to help about that.

The §6.5.16.1 Simple assignment section of the C11 standard (see n1570 draft page 102) lists a set of constraints regarding assignment, and array assignment don't fit there. Hence it is forbidden. A rule of thumb is that only scalars (that includes pointers and numerical l-values ) or struct -s can appear on the left hand side of an assignment (or be return -ed from a function).

Community's user avatar

  • Sorry, I dont understand. why test->mem[0] = 1; working and test->mem = {1,2,3,4,5,6}; doesn't? –  Nir Commented Jan 22, 2014 at 20:44
  • 1 I do not see how the statement “Arrays are not pointers” is relevant. The code in the question does not attempt to use a pointer as an array or vice-versa. The problem is attempting an assignment using initialization syntax. –  Eric Postpischil Commented Jan 22, 2014 at 20:44
  • 1 @EricPostpischil I believe that it became relevant with the latest edit to the question. –  ApproachingDarknessFish Commented Jan 22, 2014 at 20:50
  • @ValekHalfHeart: The edit tries to assign one array to another, not to use an array as a pointer or vice-versa. The error message mentions the pointer that has been produced from the array, but that is not the OP’s intent. –  Eric Postpischil Commented Jan 22, 2014 at 20:58

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c arrays gcc struct or ask your own question .

  • The Overflow Blog
  • Where does Postgres fit in a world of GenAI and vector databases?
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • What does it say in the inscriptions on Benjamin's doorway; A Canticle for Leibowitz
  • My colleagues and I are travelling to UK as delegates in an event and the company is paying for all our travel expenses. what documents are required
  • Simple casino game
  • What is the difference between using a resistor or a capacitor as current limiter?
  • Change output language of internal commands like "lpstat"?
  • Does the Greek used in 1 Peter 3:7 properly translate as “weaker” and in what way might that be applied?
  • What issues are there with my perspective on truth?
  • Odd string in output ̄[2000/12/14 v1.0] in tufte style
  • Using "no" at the end of a statement instead of "isn't it"?
  • What to do when 2 light switches are too far apart for the light switch cover plate?
  • Flyback Controller IC identification
  • What did the Ancient Greeks think the stars were?
  • Can you solve this median geometry problem?
  • How to volunteer as a temporary research assistant?
  • Optimal Bath Fan Location
  • Is "using active record pattern" a reason to inherit from standard container (eg:vector)?
  • What happens when a helicopter loses the engine and autorotation is not initiated?
  • What was I thinking when I made this grid?
  • What happens if all nine Supreme Justices recuse themselves?
  • Completely introduce your friends
  • Can a rope thrower act as a propulsion method for land based craft?
  • Why doesn't the world fill with time travelers?
  • 3 Aspects of Voltage that contradict each other
  • Why does Russia strike electric power in Ukraine?

assignment to expression with array type struct

IMAGES

  1. Array : "error: assignment to expression with array type error" when I

    assignment to expression with array type struct

  2. assignment to expression with array type

    assignment to expression with array type struct

  3. [Solved] "error: assignment to expression with array type

    assignment to expression with array type struct

  4. Array Type Assignment: Explained And Illustrated

    assignment to expression with array type struct

  5. C Programming Tutorial

    assignment to expression with array type struct

  6. Array : Matlab array of struct : Fast assignment

    assignment to expression with array type struct

COMMENTS

  1. "error: assignment to expression with array type error" when I assign a

    assignment operator shall have a modifiable lvalue as its left operand. and, regarding the modifiable lvalue, from chapter §6.3.2.1. A modifiable lvalue is an lvalue that does not have array type, [...] You need to use strcpy() to copy into the array.

  2. How to solve "Error: Assignment to expression with array type" in C

    Now let's create an instance of this struct and try to assign a value to the "string" variable as follows: struct struct_type s1; s1.struct_name = "structname"; // Error: Assignment to expression with array type. As expected, this will result in the same "Error: Assignment to expression with array type" that we encountered in the ...

  3. Understanding The Error: Assignment To Expression With Array Type

    The "Assignment to Expression with Array Type" occurs when we try to assign a value to an entire array or use an array as an operand in an expression where it is not allowed. In C and C++, arrays cannot be assigned directly. Instead, we need to assign individual elements or use functions to manipulate the array.

  4. C Structures (structs)

    Unlike an array, a structure can contain many different data types (int, float, char, etc.). Create a Structure. You can create a structure by using the struct keyword and declare each of its members inside curly braces: ... prog.c:12:15: error: assignment to expression with array type.

  5. Structure Assignment (GNU C Language Manual)

    15.13 Structure Assignment. Assignment operating on a structure type copies the structure. The left and right operands must have the same type. Here is an example: Notionally, assignment on a structure type works by copying each of the fields. Thus, if any of the fields has the const qualifier, that structure type does not allow assignment:

  6. Error: Assignment To Expression With Array Type (Resolved)

    Here are some tips to help you resolve array assignment issues: 1. Use a loop to assign values to an array. One way to assign values to an array is by using a loop. Here is an example: arr[i] = i+1; In the above example, we used a loop to assign values to the arr array. 2.

  7. Array declaration

    Array is a type consisting of a contiguously allocated nonempty sequence of objects with a particular element type. The number of those objects (the array size) never changes during the array lifetime. ... can assign structs holding array members Array to pointer conversion. Any lvalue expression of array type, when used in any context other ...

  8. Why do I get: "error: assignment to expression with array type"

    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. edited Oct 28, 2022 at 14:48. knittl.

  9. Array of Structures in C

    Here arr_car is an array of 10 elements where each element is of type struct car. We can use arr_car to store 10 structure variables of type struct car. To access individual elements we will use subscript notation ( []) and to access the members of each element we will use dot (.) operator as usual. 1. 2.

  10. CS31: Intro to C Structs and Pointers

    C Stucts and Pointers. This is the second part of a two part introduction to the C programming language. It is written specifically for CS31 students. The first part covers C programs, compiling and running, variables, types, operators, loops, functions, arrays, parameter passing (basic types and arrays), standard I/O (printf, scanf), and file ...

  11. Struct declaration

    If a struct defines at least one named member, it is allowed to additionally declare its last member with incomplete array type. When an element of the flexible array member is accessed (in an expression that uses operator . or -> with the flexible array member's name as the right-hand-side operand), then the struct behaves as if the array member had the longest size fitting in the memory ...

  12. Assignment to Expression With Array Type

    **Error1 : assignment to expression with array type (line 13, line 29)** Reason : You cannot directly assign to an array. Solution : You need to use strcpy() to copy into the array.

  13. W3Schools Tryit Editor

    prog.c:12:15: error: assignment to expression with array type 12 | s1.myString = "Some text"; // Assign a value to the string ...

  14. Getting C error "assignment to expression with array type"

    It modifies the length of the value stored. With %f you are attempting to store a 32-bit floating point number in a 64-bit variable. Since the sign-bit, biased exponent and mantissa are encoded in different bits depending on the size, using %f to attempt to store a double always fails` (e.g. the sign-bit is still the MSB for both, but e.g. a float has an 8-bit exponent, while a double has 11 ...

  15. Can't access an array-type member of a structure?

    Because you are then only accessing a single item in the array, whereas in your code you are trying to access the whole array at once. In the following codes, I can access the whole array and also an item of the array. Serial.println (birthday.name); Serial.println (birthday.name [0]); The concern to me is that -- while the following code works ...

  16. assignment to expression with array type

    How to fix the error:assignment to expression with array type#syntax #c #howto #clanguage #error #codeblocks

  17. assignment to expression with array type struct

    How to solve "Error: Assignment to expression with array type" in C? In C programming, you might have encountered the " Error: Assignment to expression with array type ".

  18. C language assignment to expression with array type

    That's the way the language goes: you cannot assign to an array, full stop. You can assign to pointers, or copy arrays with memcopy, but never try to assign to an array. BTW, char a={"a"}; is a horror: a is a single character while "a" is a string literal that is the const array {'a', '\0'}. Please use char a = 'a'; for a single char or char a ...

  19. Structure Assignment (GNU C Language Manual)

    When a structure type has a field which is an array, as here, char *name; int data[4]; }; structure assigment such as r1 = r2 copies array fields' contents just as it copies all the other fields. This is the only way in C that you can operate on the whole contents of a array with one operation: when the array is contained in a struct.

  20. C Programming: error: assignment to expression with array type

    It is a lower-level concept actually. If we say char nom[20] than its memory location will be decided at compile time and it will use stack memory (see the difference between stack memory and heap memory to gain more grasp on lover level programming). so we need to use it with indexes.. such as, nom[0] = 'a'; nom[1] = 'b'; // and so on. On the other hand if we create a string using the double ...

  21. Assign to array in struct in c

    An expression such as x = value is an assignment and cannot use the syntax for initializations. ... Arrays are not pointers (but arrays decay to pointers, see this), and you cannot assign arrays (only initialize them, or assign struct-s containing them). You could copy the array, e.g.