[c] "error: assignment to expression with array type error" when I assign a struct field (C)

I'm a beginner C programmer, yesterday I learned the use of C structs and the possible application of these ones about the resolution of specific problems. However when I was experimenting with my C IDE (Codeblocks 16.01) in order to learn this aspect of C programming, I've encountered a strange issue. The code is the following:

#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;
}

During the compilation, the compiler (GCC 4.9.3-1 under Windows) reported me an error that says

"error: assignment to expression with array type error"

on instruction

s1.name="Paolo" 
s1.surname="Rossi" 

while if I do

data s1 = {"Paolo", "Rossi", 19};

it works. What am I doing wrong?

This question is related to c arrays string struct initialization

The answer is


You are facing issue in

 s1.name="Paolo";

because, in the LHS, you're using an array type, which is not assignable.

To elaborate, from C11, chapter §6.5.16

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.

That said, data s1 = {"Paolo", "Rossi", 19}; works fine, because this is not a direct assignment involving assignment operator. There we're using a brace-enclosed initializer list to provide the initial values of the object. That follows the law of initialization, as mentioned in chapter §6.7.9

Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.[....]


typedef struct{
     char name[30];
     char surname[30];
     int age;
} data;

defines that data should be a block of memory that fits 60 chars plus 4 for the int (see note)

[----------------------------,------------------------------,----]
 ^ this is name              ^ this is surname              ^ this is age

This allocates the memory on the stack.

data s1;

Assignments just copies numbers, sometimes pointers.

This fails

s1.name = "Paulo";

because the compiler knows that s1.name is the start of a struct 64 bytes long, and "Paulo" is a char[] 6 bytes long (6 because of the trailing \0 in C strings)
Thus, trying to assign a pointer to a string into a string.

To copy "Paulo" into the struct at the point name and "Rossi" into the struct at point surname.

memcpy(s1.name,    "Paulo", 6);
memcpy(s1.surname, "Rossi", 6);
s1.age = 1;

You end up with

[Paulo0----------------------,Rossi0-------------------------,0001]

strcpy does the same thing but it knows about \0 termination so does not need the length hardcoded.

Alternatively you can define a struct which points to char arrays of any length.

typedef struct {
  char *name;
  char *surname;
  int age;
} data;

This will create

[----,----,----]

This will now work because you are filling the struct with pointers.

s1.name = "Paulo";
s1.surname = "Rossi";
s1.age = 1;

Something like this

[---4,--10,---1]

Where 4 and 10 are pointers.

Note: the ints and pointers can be different sizes, the sizes 4 above are 32bit as an example.


Please check this example here: Accessing Structure Members

There is explained that the right way to do it is like this:

strcpy(s1.name , "Egzona");
printf( "Name : %s\n", s1.name);

Questions with c tag:

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf? How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption How does one set up the Visual Studio Code compiler/debugger to GCC? How to add a char/int to an char array in C? Fork() function in C Warning comparison between pointer and integer Unsigned values in C How to run C program on Mac OS X using Terminal? How to printf a 64-bit integer as hex? Casting int to bool in C/C++ Significance of ios_base::sync_with_stdio(false); cin.tie(NULL); "Multiple definition", "first defined here" errors error C4996: 'scanf': This function or variable may be unsafe in c programming Fatal error: iostream: No such file or directory in compiling C program using GCC What is the symbol for whitespace in C? How to change text color and console color in code::blocks? How to build x86 and/or x64 on Windows from command line with CMAKE? error: expected primary-expression before ')' token (C) C compile : collect2: error: ld returned 1 exit status How to use execvp() What does "collect2: error: ld returned 1 exit status" mean? socket connect() vs bind() fatal error: mpi.h: No such file or directory #include <mpi.h> How to scanf only integer? Abort trap 6 error in C Can someone explain how to append an element to an array in C programming? Returning string from C function Difference between using Makefile and CMake to compile the code How to convert const char* to char* in C? C convert floating point to int "break;" out of "if" statement? How to compile and run C in sublime text 3? How do I use setsockopt(SO_REUSEADDR)? Reading string by char till end of line C/C++ How to set all elements of an array to zero or any same value? The differences between initialize, define, declare a variable how to stop a loop arduino 'readline/readline.h' file not found size of uint8, uint16 and uint32? warning: control reaches end of non-void function [-Wreturn-type] Char Comparison in C

Questions with arrays tag:

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array? How to update an "array of objects" with Firestore? How to increment a letter N times per iteration and store in an array? Cloning an array in Javascript/Typescript use Lodash to sort array of object by value TypeScript enum to object array How do I check whether an array contains a string in TypeScript? How to use forEach in vueJs? Program to find largest and second largest number in array How to plot an array in python? How to add and remove item from array in components in Vue 2 console.log(result) returns [object Object]. How do I get result.name? How to map an array of objects in React How to define Typescript Map of key value pair. where key is a number and value is an array of objects Removing object from array in Swift 3 How to group an array of objects by key Find object by its property in array of objects with AngularJS way Getting an object array from an Angular service push object into array How to get first and last element in an array in java? Add key value pair to all objects in array How to convert array into comma separated string in javascript Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0) Angular 2 declaring an array of objects How can I loop through enum values for display in radio buttons? How to convert JSON object to an Typescript array? Angular get object from array by Id Add property to an array of objects Declare an array in TypeScript ValueError: all the input arrays must have same number of dimensions How to convert an Object {} to an Array [] of key-value pairs in JavaScript Check if a value is in an array or not with Excel VBA TypeScript add Object to array with push Filter array to have unique values remove first element from array and return the array minus the first element merge two object arrays with Angular 2 and TypeScript? Creating an Array from a Range in VBA "error: assignment to expression with array type error" when I assign a struct field (C) How do I filter an array with TypeScript in Angular 2? How to generate range of numbers from 0 to n in ES2015 only? TypeError: Invalid dimensions for image data when plotting array with imshow()

Questions with string tag:

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript How to change the datetime format in pandas How to write to a CSV line by line? convert string to number node.js "error: assignment to expression with array type error" when I assign a struct field (C) Remove 'b' character do in front of a string literal in Python 3 Ruby: How to convert a string to boolean What does ${} (dollar sign and curly braces) mean in a string in Javascript? How do I make a new line in swift converting json to string in python PHP - remove all non-numeric characters from a string C# - How to convert string to char? How can I remove the last character of a string in python? Converting std::__cxx11::string to std::string How to convert string to date to string in Swift iOS? Convert time.Time to string TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3 How can I capitalize the first letter of each word in a string using JavaScript? Best way to verify string is empty or null Hive cast string to date dd-MM-yyyy Check for special characters in string How to convert any Object to String? Print "\n" or newline characters as part of the output on terminal Set the maximum character length of a UITextField in Swift How do I convert a Python 3 byte-string variable into a regular string? What does $ mean before a string? Delete the last two characters of the String Splitting a string into separate variables Figure out size of UILabel based on String in Swift Matching strings with wildcard How do I concatenate strings? Print very long string completely in pandas dataframe Check string for nil & empty Convert float to string with precision & number of decimal digits specified? How do I print my Java object without getting "SomeType@2f92e0f4"? enum to string in modern C++11 / C++14 / C++17 and future C++20 How should I remove all the leading spaces from a string? - swift Convert array to JSON string in swift Swift extract regex matches Convert a file path to Uri in Android How would I get everything before a : in a string Python

Questions with struct tag:

How to search for an element in a golang slice "error: assignment to expression with array type error" when I assign a struct field (C) How to set default values in Go structs How to check for an empty struct? error: expected primary-expression before ')' token (C) Init array of structs in Go How to print struct variables in console? Why Choose Struct Over Class? How to return a struct from a function in C++? Initializing array of structures Array of structs example error: expected unqualified-id before ‘.’ token //(struct) C - function inside struct Passing structs to functions Overloading operators in typedef structs (c++) default value for struct member in C C - freeing structs Function for C++ struct Initializing a struct to 0 malloc an array of struct pointers How do you make an array of structs in C? Passing struct to function GCC: array type has incomplete element type forward declaration of a struct in C? Copy struct to struct in C Invalid application of sizeof to incomplete type with a struct C - error: storage size of ‘a’ isn’t known struct in class Vector of structs initialization Incompatible implicit declaration of built-in function ‘malloc’ Initialize/reset struct to zero/null How do I check if a variable is of a certain type (compare two types) in C? Convenient C++ struct initialisation Proper way to initialize C++ structs No == operator found while comparing structs in C++ How to convert string to IP address and vice versa Copying one structure to another How to initialize struct? Structure padding and packing How to convert a structure to a byte array in C#? How to correctly assign a new string value? C/C++ Struct vs Class Struct memory layout in C C++, how to declare a struct in a header file dereferencing pointer to incomplete type struct.error: unpack requires a string argument of length 4 C programming: Dereferencing pointer to incomplete type error Define a struct inside a class in C++ Struct with template variables in C++ Assign one struct to another in C

Questions with initialization tag:

"error: assignment to expression with array type error" when I assign a struct field (C) How to set default values in Go structs How to declare an ArrayList with values? Initialize array of strings Initializing a dictionary in python with a key value and no corresponding values Declare and Initialize String Array in VBA VBA (Excel) Initialize Entire Array without Looping Default values and initialization in Java Initializing array of structures C char array initialization Double array initialization in Java Why is list initialization (using curly braces) better than the alternatives? How to fill Matrix with zeros in OpenCV? Declare and initialize a Dictionary in Typescript Initializing entire 2D array with one value Array[n] vs Array[10] - Initializing array with variable vs real number JavaFX: How to get stage from controller during initialization? C++ float array initialization initializing strings as null vs. empty string Initializing a struct to 0 Object creation on the stack/heap? c++ string array initialization How do I initialize an empty array in C#? When are static variables initialized? Cannot instantiate the type List<Product> Java check to see if a variable has been initialized Initialize/reset struct to zero/null C++: Where to initialize variables in constructor How to directly initialize a HashMap (in a literal way)? Initializing multiple variables to the same value in Java Convenient C++ struct initialisation Initialize a byte array to a certain value, other than the default null? Compiler error: "initializer element is not a compile-time constant" Best way to initialize (empty) array in PHP Proper way to initialize C++ structs How to initialize an array of objects in Java What is the correct way to start a mongod service on linux / OS X? JavaScript check if variable exists (is defined/initialized) Initialize static variables in C++ class? 2D array values C++ How to initialize an array in one step using Ruby? How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example) How to initialize struct? Assign multiple values to array in C What is the default initialization of an array in Java? Array initialization in Perl Declaring and initializing arrays in C How do C++ class members get initialized if I don't do it explicitly? Error "initializer element is not constant" when trying to initialize variable with const How to initialize var?