C Programming: Understanding String Literals and Pointers
C Programming: Working with String Literals and Pointers
This example demonstrates how to use pointers in C to handle string literals.
char *p;
p = 'hello';
printf('%s', p);
Output: hello
Explanation:
-
Declaring a Pointer: We declare a pointer variable
pof typechar. This meanspcan hold the address of a character in memory. -
Assigning the String Literal: We assign the address of the string literal 'hello' to the pointer
p. String literals are stored in a read-only section of memory. -
Printing the String: The
printf()function uses the%sformat specifier, which expects a pointer to a null-terminated string. Sinceppoints to the beginning of the string 'hello',printf()will print the entire string until it encounters a null character ('\0') at the end of the string literal.
Key Points:
- String literals in C are implicitly null-terminated, meaning they have a null character (
\0) at the end, which marks the end of the string. - Pointers are powerful tools in C for accessing and manipulating data in memory. Understanding how they interact with string literals is crucial for working with text and strings in your programs.
原文地址: https://www.cveoy.top/t/topic/nyqZ 著作权归作者所有。请勿转载和采集!