Home > Backend Development > C++ > body text

What\'s the Difference between `char*` and `char[]` in C?

Barbara Streisand
Release: 2024-10-27 04:47:02
Original
628 people have browsed it

 What's the Difference between `char*` and `char[]` in C?

Understanding the Distinction between char* and char[]

When dealing with character arrays and pointers in C programming, it's crucial to grasp the fundamental differences between char str[] = "Test"; and char *str = "Test";.

char str[] = "Test";

In this declaration, str represents an array of characters (chars) with a fixed size, initialized with the contents of the string "Test". The array owns its own memory and is distinct from the original string literal. Any modifications to str will alter the local copy of the data, not the "Test" string itself.

char *str = "Test";

Here, str is a pointer, specifically a pointer to the first character of the string literal "Test". The pointer stores the memory address of this character. However, it's crucial to remember that str does not own the memory where the string is stored; instead, it points to the read-only (const) string literal. Consequently, any attempt to change the string pointed to by str will result in undefined behavior.

Key Differences:

  1. Ownership: char[] arrays own their data, while char* pointers reference data owned by another entity.
  2. Mutability: char[] arrays can be modified (e.g., assigned new values), but char* pointers point to immutable literals, and changing the data they point to is undefined.
  3. Memory Allocation: char[] arrays allocate local memory on the stack, whereas char* pointers can refer to memory anywhere in the program, including literals and other allocated memory.
  4. Size Determination: The size of char[] arrays is fixed at compile-time, while the size of data pointed to by char* pointers is determined by the data itself or by the allocation of external memory.

The above is the detailed content of What\'s the Difference between `char*` and `char[]` in C?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!