In C language, Why can a string be assigned to character pointer variables in C language character array and string Pointer Analysis?

Source: Internet
Author: User

This article uses several postsArticleThe content is slightly modified:

I,

Why can a string be assigned to a character pointer variable in C?

Char * P, A = '5 ';
P = & A; // It is obviously correct,
P = "ABCD"; // but why can I assign a value like this ??

Q: I have never understood why I can assign a String constant to a character pointer variable. Please give me some advice! 

A:Double quotation marks do three things: 
1. Applied for space (in the constant area) and stored strings
2. Add '/0' to the end of the string'
3. Return address

Here, the returned address is assigned to P.

II,

Char * P = "hello ";

Why can the above expression be used, instead of changing P to an array and then assigning a value?

Explanation:

When the String constant "hello" appears in an expression,"The value used by the hello "expression is the address stored by these characters (in the constant area), rather than the characters themselves.

Therefore, you can assign a string to the pointer P pointing to the character, rather than a character array. 

Char A [10] = "hello"; // This is acceptable. In this caseC LanguageInitialize the supported

If it is written as char a [10]

Then a = "hello" is incorrect. 

It is also an array of A, char a [10] = "hello"; this is the initialization of the array, and a [0] = 'h'a [1] = 'E '... Is a truth

But changed to char a [10].

Then a = "hello" won't work. The value assigned by "hello" is an address. Although a also has an address, it is different from the pointer. the pointer value is an address, although the array value is an address, it is a constant, so it cannot be assigned a value.

CodeTest

# Include <stdio. h> 

Int main ()

{

Char * P = "hello ";

Printf ("% s", P );

Char A [10];

A = "hello ";

Return 0;

}

Error c2440: '=': cannot convert from 'Char [6] 'to 'Char [10]'

There is no context in which this conversion is possible

Will you think of changing char a [10] To char a [6 ]?

Give it a try,

Error c2106: '=': left operand must be L-Value

The left side of the operator is a "Left value ". The so-called "Left value" refersProgramMemory usage, the amount that can be modified, such as various variables.

 

Questions about continued expansion:

When using pointers, pointers can be auto-incremented, while arrays cannot.

The compiler allocates space to the array, and the address of array A is a constant. It is definitely not feasible to allow Constant Auto-increment. 

Continue expansion:

When the pointer is auto-incrementing, the compiler automatically recognizes the type.,For example, the Pointer Points to the int type. When you want to get the next address, the pointer can be directly P ++.

Note that when using the void pointer, you cannot use pointer operations. It should be the void compiler that cannot recognize the length of the type (that is, the volume of the object indicated by the pointer ), P ++ is invalid, that is, it cannot be used for mathematical operations or * value operations. To use a value, you must convert it to another type.

 

III,

Title:Character array, character pointer, String constantOriginal post address: http://anypath.blog.sohu.com/25069424.html

1. If it appears as a string, the compiler will automatically add a 0 to the string as the end character, as shown in the code
"ABC", the compiler will help you store "ABC \ 0"

2. Is "ABC" a constant? The answer is sometimes, sometimes not.

Not a constant :"ABC"The initial value of the character array is not, Such
Char STR [] = "ABC ";
Because it defines a character array, it is equivalent to defining some space to store "ABC ".
The character array stores the characters one by one, so the compiler resolves this statement
Char STR [3] = {'A', 'B', 'C '};
According to the conclusion 1 above, the final result of char STR [] = "ABC"; is
Char STR [4] = {'A', 'B', 'C', '\ 0 '};
If char STR [] = "ABC"; is written inside the function
Of"ABC \ 0" should be placed on the stack because it is not a constant.

Is a constant: When "ABC" is assigned to a character pointer variable, such
Char * PTR = "ABC ";
Because it defines a normal character pointer and there is no space to define "ABC", the compiler has to help us
Find a place to put "ABC ",Obviously, the "ABC" here is treated as a constant and put it in the constant area of the program as a compiler.
The most suitable choice.Therefore, although the PTR type is not const char *, and PTR [0] = 'X'; can also be compiled
But run PTR [0] = 'X '; Runtime exception Because this statement tries to modify the program
Something in the constant area.
I remember which book once said char * PTR = "ABC"; this method was originally not allowed in the C ++ standard,
However, this writing method is too many in C. to be compatible with C, it is not allowed. Although allowed,
HoweverThe recommended method is const char * PTR = "ABC". In this way, if PTR [0] = 'X' is followed
Then, the compiler will not let it pass the compilation, thus avoiding the running exception mentioned above.
Expand again. If char * PTR = "ABC"; is written in the function body, although "ABC \ 0" is
Put it in the constant area, but PTR itself is just a common pointer variable, so PTR is placed on the stack,
It's just that what it points to is put in the constant area.

3.The array type is determined by the type of the items stored in the array and the size of the array.
For example, char S1 [3] and char S2 [4], S1 is Char [3], S2 is Char [4],
That is to sayAlthough S1 and S2 are character arrays, their types are different..

4.The type of A String constant can be understood as the type of the corresponding character constant array.,
For example, the "abcdef" type can be considered as const char [7].

5. sizeof is used to calculate the number of bytes of the type. For example, int A; either sizeof (INT) or sizeof ()
Is equal to 4, because sizeof (a) is actually sizeof (type of)

6.For parameters written as arrays in the function parameter list, the compiler interprets them as common
Pointer typeFor example, for void func (char SA [100], int Ia [20], char * P)
The SA type is char *, IA type is int *, and p type is char *

7. Based on the above summary, let's take a look at the actual situation:
For char STR [] = "abcdef"; there is sizeof (STR) = 7, because the STR type is Char [7],
There are also sizeof ("abcdef") = 7, because the type of "abcdef" is const char [7].
For char * PTR = "abcdef"; there is sizeof (PTR) = 4, because the PTR type is char *.
For char str2 [10] = "abcdef"; there is sizeof (str2) = 10, because the str2 type is Char [10].
For void func (char SA [100], int Ia [20], char * P );
There is sizeof (SA) = sizeof (IA) = sizeof (p) = 4,
Because the SA type is char *, IA type is int *, and p type is char *.

IV,

C language character array and string Pointer Analysis, the post original address: http://www.cnblogs.com/gigikouyi/archive/2006/08/01/464737.html

In the past few days, many character arrays and string pointers have been used in C Programs on Unix. I remember that after I learned the C language for quite some time, I am still confused about the pointer, later, I didn't use C in my work. Even though there are many such articles on the internet, I decided to make a small summary here, and I felt better, I wrote the following test program:

# Include <stdio. h>

Int main (INT argc, char * argv [])
{

Char day [15] = "abcdefghijklmn ";
Char * strtmp = "opqrstuvwxyz ";

Printf ("& Day is % x \ n", & Day );
Printf ("& day [0] is % x \ n", & day [0]);
Printf ("Day is % x \ n", Day );

Printf ("\ n & strtmp is % x \ n", & strtmp );
Printf ("& strtmp [0] is % x \ n", & strtmp [0]);
Printf ("strtmp is % x \ n", strtmp );

Getchar ();
Return 0;
}

The following result is displayed on the screen after running:

In fact, it is easy to understand a lot of things when you see the results,

Let's take a look at the first three outputs, that is, about the variable Day, in char day [15] = "abcdefghijklmn"; when this statement is executed, the system allocates a 15-Bit Memory Length, and name the memory as day, and the value in it is "abcdefghijklmn", as shown in:

Let's look at the program. The first output, & day, & number is the address operator, that is, the memory address of the day variable. Obviously, at the beginning, that is, the address of the byte where the character is located;
The second output is well understood. & day [0] is the address of the first variable (that is, a) in the day array, so they are the same;
The third output is day. For an array variable, you can use the variable name to index the content in the Variable. In fact, the day here can be understood as the degraded pointer of the array variable and point to the beginning of the array, since it is understood as a pointer, its value must be an address, so its value is the same as the above two.

Let's look at the following three outputs. For the string pointer strtmp, after running char * strtmp = "opqrstuvwxyz";, the memory diagram is as follows:

The memory is allocated with two segments of memory, one is strtmp, the type is a character pointer, the other is a String constant, and the strtmp contains the first address of the character constant, note that this string cannot be modified through strtmp, because it is a constant, so the next three outputs in the program are easy to understand;

& Strtmp: strtmp character pointer address
& Strtmp [0]: Address of the first character of the character constant specified by strtmp
Strtmp: the value of the strtmp character pointer, that is, the first address of the character constant

Therefore, the last two values are the same.
The pointer type is the same as int, Char, double, and so on, but it is used to save the address value, while the int variable saves the integer and the char variable saves the character, that's all. Char or Int pointers are essentially the same. They are all stored addresses, but the types of variables in the address are different. There is also a void pointer, is the address where any type of variable can be placed.

5. Personal Code and comments are purely a personal understanding. If something is wrong, I hope to criticize and correct it:

# Include <stdio. h>

Int main (INT argc, char * argv [])
{
Char * strtmp = "ABCD ";
Printf ("strtmp is % s \ n", strtmp); // converts the content implied by the address of the String constant "ABCD" to "string type"
Printf ("strtmp is % d \ n", strtmp); // converts the address of the String constant "ABCD" to the int type, the running results of different machines may be different at different times, because the address may change.
Printf ("strtmp is % C \ n", strtmp); // converts the address of the String constant "ABCD" to the bytes type, the running results of different machines may be different at different times, because the address may change.
Printf ("* strtmp is % C \ n", * strtmp); // converts the content implied by the address of the String constant "ABCD" to the bytes type, the following comments will throw an exception. We can see that no string is intercepted here. * The strtmp length is 1.
// Printf ("* strtmp is % s \ n", * strtmp); // The character cannot be converted into a string
Getchar ();
Return 0;
}

6. Later I saw the following statement for your reference:

1. There is no string type in C, which is represented only by character arrays. This is different from the string in C ++. Strings in C ++ can be directly assigned values such as string s; S = "Hello World "; however, the character array in C language cannot. Therefore, the strtmp here can be understood as the first address of the character array, or it can be used to represent the entire character array, so it can output the content of all character arrays.

2. A string is a character array or pointer. The memory implementation is the same. The array name is a pointer.

Char ch [100];
Char * P;
P = CH;

3. Example of the defined string method:

String definition is actually very simple. You can use the following syntax to define a string in C/C ++:

Char * S1 = "string1"; // defines a String constant in the pointer format.

Char S2 [] = "string2"; // defines string constants in the array format

Char * S3 = new char [10]; // defines string variables and allocates memory pointers

Strcpy (S3, "string3"); // assign a value to S3

Char S4 [10]; // defines string variables in the array format

Strcpy (S4, "string4"); // assign a value to S4

The above four methods can define a string, and the distribution of strings in the memory can clearly know what the situation is.

 

4. in C language, strcpy (char * D, char * s) represents the source string, D represents the target string, that is, the string you want to assign a value.

5. the strings in C language are different from those in Java or C ++. For example, char * P; where p is a pointer,P stores the first address of a memory buffer.. The so-calledThe memory buffer is a continuous memory address, which stores a series of characters.Then how does the system determine where it ends. It is based on the '\ 0' symbol '. This character occupies one byte, eight bits, and each value is 0.

 

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.