How to Assign Values to an Array of Characters in C – C

Photo of author
Written By M Ibrahim
abstractclass arrays assignmentoperator fstring
Quick Fix: Use the strcpy function from the string.h library to copy the desired string into the character array. For example, strcpy(word, “Jump”);

The Problem:

When attempting to assign values to an array of characters in C, such as in the provided code, the error message "array type char[30] is not assignable" is encountered. This error occurs because arrays in C are not assignable directly.

The Solution:

Solution 1: Using strcpy

To assign values to a character array in C, you need to use a library function like strcpy. The strcpy function allows you to copy the contents of one string into another. In this case, you can use strcpy(word, "Jump"); to assign the string "Jump" to the character array "word".

Solution 2: Using memcpy

Another option is to use the memcpy function. The memcpy function allows you to copy a specified number of bytes from one memory location to another. In this case, you can use memcpy(word, "Jump", sizeof("Jump")); to assign the string "Jump" to the character array "word".

Conclusion:

In C, arrays of characters cannot be directly assigned values using the assignment operator. Instead, you need to use library functions like strcpy or memcpy to copy the desired string into the character array. By following these solutions, you can successfully assign values to character arrays in C.

Sources: