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.

  1. 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;
}
  1. Create a pointer named ‘str’ pointing to the string “Hello”.
#include <stdio.h>

int main() {
    char *str = "Hello";
    printf("%s\n", str);
    return 0;
}
  1. 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:

  1. Use a character array: char str[10];
  2. Use a character pointer: char *str;
  3. Initialize an array of characters using an initialization list: char str[];
bannerAds