About string arrays and string constants in C + +

Source: Internet
Author: User
Tags constant
Today encountered a lot of problems, from memory to string ... On the Internet to check some information, now on the string array and string constants to make a summary of it.
In fact, char sz[] = "string";  and char *psz = "string"; The difference between the assignment of these two strings.

First of all say char sz[] = "string"; This statement, which is stored in the form of an array, is interpreted by the compiler as
Char sz[] = {' s ', ' t ', ' r ', ' I ', ' n ', ' g ', '/0 '}; If it appears inside the function, these characters will be stored on the stack, so it is not a string constant.

Again, char *psz = "string"; This statement, which defines a pointer to a "string" string and has no space for a "string" string, and it is obvious that "string" as a string constant and stored in a constant area is the most appropriate choice. And the statement psz[4] = ' x '; An error is not generated at compile time, and an exception occurs when execution occurs because "string" is stored in a read-only storage area and cannot be modified. This is the same as the const char *PSZ = "string" in C + +, so it is best to display the Const keyword so that the compiler detects a "modify constant" error.

A problem that has not been understood before: what to think when a row parameter of a function is an array.
such as: void Foo (char sz[100], int ival[10]);
The answer is to interpret it as the form of a pointer:
void Foo (char *sz, int *ival);
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.