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:

  1. Declaring a Pointer: We declare a pointer variable p of type char. This means p can hold the address of a character in memory.

  2. 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.

  3. Printing the String: The printf() function uses the %s format specifier, which expects a pointer to a null-terminated string. Since p points 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.
C Programming: Understanding String Literals and Pointers

原文地址: https://www.cveoy.top/t/topic/nyqZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录