How to assign value to a string in C language?
In the C language, strings can be assigned in the following ways:
- Use an array of characters:
- Assign the string directly to the character array in str1 and use the strcpy function to assign the string to the character array in str2.
- Utilize pointer variables:
- str3 points directly to the string “Hello.”
str4, previously declared, is assigned the string “World.” - Assign values one by one using the index of the character array.
- The character array str5 is initialized with the string “Hello”, with a null terminator ‘\0’ at the end to mark the end of the string.
It is important to note that when using character arrays for assignment, the array must be large enough to accommodate the string and the string’s terminating character ‘\0’. When using pointer variables for assignment, the pointer can point to a string of any length, but the string itself must end with ‘\0’.