Character array, character pointer-related issues

Source: Internet
Author: User

One

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

Char *p,a= ' 5 ';
p=&a; is clearly correct,
P= "ABCD"; But why is it possible to assign values like this??

Q: I can't understand why you can assign a string constant to a character pointer variable, please! Answer: Double quotes do 3 things:
1. Application space (in the constant area), storing the string
2. Add '/0 ' at the end of the string
3. Return address

This is where you return the address assigned to P.


Second,

char *p = "Hello";

Why is the expression above, instead of changing p to an array and then assigning a value?

Explain:

When the string constant "Hello" appears in an expression, the value used by the "hello" expression is the address that these characters store (in the constant area), not the characters themselves.

So, you can assign a string to a pointer to a character p, and not a string to a character array.

Char a[10] = "Hello"; This allows the C language initialization to be supported

If written as Char a[10]

Then a = "Hello" is wrong.

The same is 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 char a [10]

Then a = "Hello" is not the value of the "Hello" assignment is an address, and a although there is an address, but this is not the same as the pointer, the value of the pointer is an address, and the value of the array is an address, but it is a constant, so you cannot assign a value to a constant.

Code testing

#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

If you see such an error, would you think of changing char a[10] to char a[6]?

Try it,

Error C2106: ' = ': Left operand must is L-value

The left side of the operator should be a "left value". The so-called "lvalue" refers to the amount of memory space in the program that can be modified, such as various variables.

Continue to expand the issue:

Pointers can be self-increment when using pointers, and arrays cannot be self-increment

The compiler allocates space to the array, and the address of the array A is a constant, and it is certainly not possible for the constant to increment itself.

Continue to expand:

When the pointer is self-increment, the compiler will automatically recognize the type, such as the pointer is to the int type, want to get the next address, the pointer p++ directly, do not superfluous p+4

It is important to note that when the void pointer is used, the pointer operation cannot be used, and that the void compiler does not recognize the length of the type (that is, the volume of the object the pointer refers to), which is p++, that is, it is not possible to perform mathematical operations, or to use the * value operation. Want to use a type that must be converted to another


Three
Title: pairs of character arrays, character pointers, string constantsOriginal address: http://anypath.blog.sohu.com/25069424.html

1. Occurs as a string, the compiler automatically adds a 0 as a terminator to the string, as in code
"ABC", then the compiler helps you store "Abc\0"

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

is not a constant condition: "ABC" ASwhen the initial value of a character array is notSuch as
Char str[] = "ABC";
Because a character array is defined, it is equivalent to defining some space to hold "abc", and because
The character array is the character that holds the characters one by one, so the compiler parses the statement into
Char str[3] = {' A ', ' B ', ' C '};
Also according to the above summary 1, so char str[] = "abc"; The end result is
Char str[4] = {' A ', ' B ', ' C ', ' n '};
Do an extension, if char str[] = "ABC"; it's written inside the function, so here
Of"Abc\0" is not a constant, so it should be placed on the stack.

is a constant condition: when assigning "abc" to a character pointer variable, such as
char* ptr = "abc";
Because the definition is a normal character pointer, and there is no space defined to hold "ABC", so the compiler has to help us
Find a place to put "ABC",Obviously, the "ABC" here as a constant and put it in the program's constant area is the compiler
The most suitable choice. So although the type of PTR is not const char*, and ptr[0] = ' x '; can also be compiled
Pass, but execute ptr[0] = ' x '; a run-time exception occurs because this statement attempts to modify the program
Something in the constant area.
Remember which book once said char* ptr = "abc", which was originally not allowed in the C + + standard,
But because this kind of writing in C is really too much, in order to be compatible with C, not allowed to be allowed. Although allowed,
Butthe suggested notation should be const char* PTR = "abc", so that if the back is written ptr[0] = ' x '
The compiler will not let it compile and avoid the run-time exception mentioned above.
Again, if char* ptr = "abc"; written in the function body, then although the "abc\0" here is
is placed in a constant area, but PTR itself is just a normal pointer variable, so PTR is placed on the stack,
It's just that what it points to is placed in a constant area.

3. The type of the array is determined by the type of things that the array holds and the size of the array itself.
such as Char S1[3] and char s2[4],s1 type is CHAR[3],S2 type is char[4],
This means that although both S1 and S2 are character arrays, the two types are different.

4. the type of a string constant can be understood as the type of the corresponding character constant array .
such as the type of "abcdef" can be regarded as a const CHAR[7]

5.sizeof is the number of bytes used to find the type. such as int A; then either sizeof (int) or sizeof (a)
is equal to 4 because sizeof (a) is actually sizeof (type of a)

6. For formal parameters written in array type in the list of function arguments, the compiler interprets it as a normal
Pointer type, such as for void Func (char sa[100],int Ia[20],char *p)
The type of the SA is Char*,ia type int*,p is char*


7. According to the above summary, to combat a bit:
For char str[] = "abcdef", there is sizeof (str) = = 7, because the type of STR 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 type of PTR 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 are sizeof (sa) = = sizeof (IA) = = sizeof (p) = = 4,
Because the type of SA is char*, the type of IA is int*,p type is char*.

Four

C language character array and string pointer analysis, the paste site: http://www.cnblogs.com/gigikouyi/archive/2006/08/01/464737.html

These days on UNIX C program, which used a lot of character array and string pointers, I remember after learning C language for quite some time, the pointer this thing is still vague, and later work did not how to use the C, although online this kind of article also has a lot, or decide oneself in this to do a small summary, Also to deepen their own impressions, wrote the following test procedures:

#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 was%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 results are available on the screen after running:


actually see the result estimate a lot of things to understand,

First look at the first three output is about the variable day, in char day[15] = "ABCDEFGHIJKLMN"; When this statement executes, the system allocates a length of 15 memory, and the memory is named Day with the value "ABCDEFGHIJKLMN" as shown:

Look at the program, the first output,&day,& is the address operator, that is, the memory address of the variable day, it is obvious that at the front, that is, the address of the byte where the a character is located;
For the second output, it's good to understand, &day[0], is the address of the first variable (that is, a) in the day array, so the two of them are the same;
The third output is day, for array variables, you can use the variable name to index the contents of the variable, in fact, the day here can understand the array of variables degenerate pointer, and point to the beginning of the arrays, since it is understood as a pointer, then its value is definitely an address, so his value and the above two is the same.

Take a look at the back three output, about the string pointer strtmp, in the execution char* strtmp = "opqrstuvwxyz", after the memory diagram is as follows:


, memory allocated two memory, one named Strtmp, the type is a character pointer, the other is a string constant, and Strtmp contains the first address of the character constant, note that there is no way to modify this string by strtmp, because it is a constant , then the three output in the program is good to understand;

&strtmp:strtmp the address of this character pointer
&strtmp[0]:strtmp the address of the first character of the indicated character constant
Strtmp:strtmp the value of this character pointer, which is the first address of the word constant

Therefore, the last two values are the same.
Pointers can be understood as pointers of this type, and int,char,double, and so on is the same, but it is used to save the address value, and the int variable holds the integer, char variable holds the character, only that, on the char pointer or int pointer, essentially the same, is the address of the store, It's just that the variable type is different in that address, and there is a void type pointer, which is the address of any type of variable that can be placed.

Personal code and comments, purely personal understanding, there is something wrong, look at criticism:

#include <stdio.h>

int main (int argc, char *argv[])
{
char* strtmp = "ABCD";
printf ("Strtmp is%s\n", strtmp);//Convert the contents of the address of the string constant "ABCD" to "String type"
printf ("Strtmp is%d\n", strtmp);//Convert the address of the string constant "ABCD" to the int type, where different machines may run differently at different times because the address may change
printf ("Strtmp is%c\n", strtmp);//Convert the address of the string constant "ABCD" to a character type, where different machines may run differently at different times because the address may change
printf ("*strtmp is%c\n", *strtmp);//Convert the contents of a string constant "ABCD" to a character type, as the following note will throw an exception, there is no truncated string, the *strtmp length itself is 1
printf ("*strtmp is%s\n", *strtmp);//cannot convert character to string type
GetChar ();
return 0;
}

Six, and then see the following statements are available for readers to refer to:

1. There is no string type in the C language and is represented only by a character array. This differs from string in C + + in that string in C + + can be directly assigned such as String s;s= "Hello World", but the character array in C is not. So, the strtmp here can be understood as the first address of a character array, or it can be used to represent an entire character array, so that the contents of all character arrays can be output.

2. A string is either a character array or a pointer. Memory implementations are the same. The array name is a pointer.

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

3. Examples of string patterns defined:

The string definition is simple. Defining a string in a C + + language can use the following syntax:

Char *s1= "string1";//define string constants, pointer form

Char s2[]= "string2";//define string constants, array form

Char *s3=new char[10];//defines a string variable and allocates a memory pointer form

strcpy (S3, "string3");//Assignment for S3

Char s4[10];//defines a string variable, in the form of an array

strcpy (S4, "String4");//Assignment for S4

All four of these methods can define a string, and the distribution of the string in memory clearly knows what the situation is.

4. The string assignment method in C language strcpy (char*d,char*s) where S is the source string, and D is the target string, which is the string you want to assign a value to.

The string in the 5.c language differs from the string in Java or C + +. such as Char *p; where P is a pointer, p stores the first address of a memory buffer. The so-called memory buffer is a contiguous memory address, which contains a series of characters. How does the system judge where it ends? That is, according to the symbol ' "". This character takes up one byte, 8 bits, and the value of each bit is 0.

Character array, character pointer-related issues

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.