c inizialize strng code example

Example 1: c inizialize strng

char c[] = "abcd";

char c[50] = "abcd";

char c[] = {'a', 'b', 'c', 'd', '\0'};

char c[5] = {'a', 'b', 'c', 'd', '\0'};

Example 2: how to create a string in c

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

Example 3: string in c

#include 

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:

Misc Example