how to make a string variable in C code example

Example 1: how to create a string in c

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char greeting[] = "Hello";

Example 2: declare string in c

char string[20];

Example 3: string in c

#include <stdio.h>
void displayString(char str[]);

int main()
{
    char str[50];
    printf("Enter string: ");
    fgets(str, sizeof(str), stdin);             
    displayString(str);     // Passing string to a function.    
    return 0;
}
void displayString(char str[])
{
    printf("String Output: ");
    puts(str);
}

Example 4: how to store string in c

char str[4] = "GfG"; /*One extra for string terminator*/

Example 5: string in c

#include <stdio.h>

int main() {
  char *str1 = strdup("Hello");
  char *str2 = malloc(sizeof(char) * (strlen(str1) + 1));
  
  for (int i = 0; i < strlen(str1); ++i)
    str2[i] = str1[i];
  str2[strlen(str1)] = '\0'; // very important, the string stop to print
  printf("%s --> %s\n", str1, str2);
}

Tags:

C Example