[C] String

chohk10·2023년 4월 3일
0

C 언어

목록 보기
3/3
post-thumbnail

String in C

In C, a string is typically represented as an array of characters, where the last character of the array is the null character '\0'. The null character serves as a sentinel value that indicates the end of the string.

To allocate space for a string in C, you can declare an array of characters with a size that is sufficient to hold the string plus the null character. For example, to allocate space for a string that contains the word "hello", you can declare an array of characters with a size of 6 to accommodate the five characters in "hello" plus the null character:

char str[6] = "hello";

In this code, str is an array of characters with a size of 6. The characters in "hello" are assigned to the first 5 elements of the array, and the null character is assigned to the 6th element.

To access individual characters in the string, you can use array indexing. For example, str[0] would give you the first character in the string ("h"), str[1] would give you the second character ("e"), and so on.

You can also use the %s format specifier with the printf() function to print out the entire string. For example:

printf("The string is: %s\n", str);

This code will output "The string is: hello\n" to the console.

Note that when declaring a string in C, it's important to make sure that the size of the array is large enough to hold the string plus the null character. If the array is not large enough to hold the string, you may encounter buffer overflow errors or other memory-related issues.

0개의 댓글