How to assign a value to a string in the C programming language?
There are two ways to assign values to strings in the C language:
- Use character array:
char str[] = "Hello, World!";
This method will copy string constants to a character array at compile time, with the size of the array automatically determined based on the length of the string.
- Using pointer variables:
char *str = "Hello, World!";
This method assigns the address of a string constant to a pointer variable, which points to the first address of the string constant. It is important to ensure that the pointer variable has enough space to store the string constant when using it for assignment.
It is important to note that a string assigned using an array of characters can be modified, whereas a string assigned using a pointer variable is read-only and cannot be directly modified. If you want to modify the string, you can store it in a character array and use the strcpy() or strncpy() function to copy the string over.