0
You have two types of strings in C however both are of type char* which is a pointer to the first char of the string.
The first is a string literal to assign a string literal in C you simple declare the char* give your variable and name and set you variable like this:
char *my_name = "William"
The second type is a char array which has several different methods of declaring depending on if you are creating a dynamic or set length array.
For a set length you can simple declare an array of chars like this
char my_name[8];
my_name[0] = 'W';
my_name[1] = 'i';
my_name[2] = 'l';
my_name[3] = 'l';
my_name[4] = 'i';
my_name[5] = 'a'
my_name[6] = 'm'
my_name[7] = '\0'
notice in this example I had to add the null char '\0' this is how the strings are terminated to know where the end is. It is not a hard stop however so you can still read past it but thats a deeper discussion.
To create a dynamic string you have to create it after you know the size of the string by allocating memory. This will create the pointer to the first indice of the char*.
char* my_name;
my_name = malloc(sizeof my_name * 8); //This give me 8 char locations in memory.
Then fill it like we did the array or many other methods.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char *my_name = "William";
printf("%s\n", my_name);
char secondName[8];
secondName[0] = 'A';
secondName[1] = 'b';
secondName[2] = 'c';
secondName[3] = 'd';
secondName[4] = 'e';
secondName[5] = 'f';
secondName[6] = 'g';
secondName[7] = '\0';
printf("%s\n", secondName);
char *thirdName;
thirdName = malloc(sizeof thirdName * 8);
puts("Enter your name:");
scanf("%7s", thirdName);
while(getchar() != '\n');
printf("%s\n", thirdName);
printf("%ld\n", strlen(thirdName));
free(thirdName);
return 0;
}
Hope that helps.



