Strings
- A set of things tied or threaded together on a thin cord
- Contiguous sequence of characters
- Stores printable ASCII characters and its extension.
- End of the string is marked with a special character, the null character '\0'
- '\0' is implicit in strings enclosed with “”
- Example: “You know, now this is what a string is!”
char char_array[5] = {'H', 'E', 'L', 'L', 'O'}; - Character ArrayProgram Example1:
char str[6] = {'H', 'E', 'L', 'L', 'O', '\0'}; - String
char str[] = {'H', 'E', 'L', 'L', 'O', '\0'}; - Valid
char str[6] = {“H”, “E”, “L”, “L”, “O”}; - Invalid
char str[6] = {“H” “E” “L” “L” “O”}; - Valid
char str[6] = {“HELLO”}; - Valid
char str[6] = “HELLO”; - Valid
char str[] = “HELLO”; - Valid
char *str = “HELLO”; - Valid
Program Example2:#include <stdio.h>Output : The size of the array Is calculated So, : 5, 6
int main()
{
char char_array_1[5] = {'H', 'E', 'L', 'L', O'};
char char_array_2[] = “Hello”;
sizeof(char_array_1);
sizeof(char_array_2);
return 0;
}
int main()
{
char *str = “Hello”;
sizeof(str);
return 0;
}
Output : The size of pointer is always constant so, : 4 (32 Bit System)
String - Manipulations:
char str1[6] = “Hello”;
char str2[6];
str2 = “World”;
Conclusion: Not possible to assign a string to a array since its a constant pointer.
char *str3 = “Hello”;
char *str4;
str4 = “World”;
Conclusion: Possible to assign a string to a pointer since its variable
Str1[0] = 'h';
Conclusion: Valid. str1 contains “hello”
Str3[0] = 'w';
Conclusion: Invalid. str3 might be stored in read only section. Undefined behavior
String - Sharing
#include <stdio.h>What could be the above output try it yourself.. :)
int main()
{
char *str1 = “Hello”;
char *str2 = “Hello”;
if (str1 == str2)
{
printf(“Yep, They share same space!\n”);
}
else
{
printf(“No, They are in different space\n”);
}
return 0;
}
Strings - Library Functions




No comments:
Post a Comment