Home > Backend Development > C++ > What's the Difference Between `char a[] = 'string';` and `char *p = 'string';` in C?

What's the Difference Between `char a[] = 'string';` and `char *p = 'string';` in C?

DDD
Release: 2024-12-17 19:56:11
Original
645 people have browsed it

What's the Difference Between `char a[] =

Difference Between "char a[] = "string";" and "char *p = "string";"

In programming, variables can be either pointers or arrays. When declaring variables, the syntax for pointers and arrays differs. Understanding the distinction between the two is crucial for correctly manipulating data.

char a[] = "string";

This line of code creates an array of characters large enough to store the string "string" along with its null-terminator. The array "a" is initialized with the elements of the string "string". An array can be modified later on, and its size is known at compile-time, allowing the use of the "sizeof" operator to determine its length.

char *p = "string";

This line of code creates a pointer named "p" that points to the address of the string "string". The pointer "p" cannot be modified, but the string it points to can, resulting in undefined behavior.

Comparison:

  • Storage: Arrays occupy continuous memory space, while pointers store the address of a memory location.
  • Modification: Arrays allow modifications to their elements, while pointers pointing to strings should not be modified as they often reside in read-only memory.
  • Size: Arrays have a fixed size, determined at compile-time, while the size of the string pointed to by a pointer must be determined using functions like "strlen()" since "sizeof" returns the size of the pointer itself.
  • Usage: Use arrays for data that needs to be modified, and pointers for data that is constant and should not be altered.

Note: The example in the question contains a typo, as "?" is not a valid operator in this context. It has been assumed that the intended question was about the difference between arrays and pointers.

The above is the detailed content of What's the Difference Between `char a[] = 'string';` and `char *p = 'string';` 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template