What is the method for defining and assigning strings in the C language?
In C language, there are several ways to define and assign strings.
- A character array named “str” with a size of 10.
#include <stdio.h>
#include <string.h>
int main() {
char str[10];
strcpy(str, "Hello");
printf("%s\n", str);
return 0;
}
- Create a pointer named ‘str’ pointing to the string “Hello”.
#include <stdio.h>
int main() {
char *str = "Hello";
printf("%s\n", str);
return 0;
}
- Initializing a character array using an initialization list: When defining a character array, you can directly use an initialization list to assign a string. Example code is shown below:
#include <stdio.h>
int main() {
char str[] = "Hello";
printf("%s\n", str);
return 0;
}
It is important to note that the above methods are used to define and assign values to strings. If you only want to define a string without assigning a value, you can use the following method:
- Use a character array: char str[10];
- Use a character pointer: char *str;
- Initialize an array of characters using an initialization list: char str[];