C ++

Source: Internet
Author: User
    1. Usage of typedef

Typedef defines an alias in a real sense, rather than a simple macro replacement.

Differences between typedef and # define:

Case 1:

Generally, typedef is better than # define, especially when there is a pointer. See the example below:

Typedef char * pstr1;

# Define pstr2 char *;

Pstr1 S1, S2;

Pstr2 S3, S4;
In the preceding variable definition, S1, S2, and S3 are both defined as char *, while S4 is defined as char, which is not the expected pointer variable, the root cause is that # define is a simple string replacement, while typedef is

Type.

Note the statement char * pA, PB. In the statement, PA is defined as a character pointer, while Pb is defined as a character variable. I have never noticed this problem. For int, it is the same. For example, int * A and B actually define a pointer and an integer. Therefore, a good programming habit should be to connect * with the variable name, rather than following the type. For example, char * pa and Pb.

Consider this problem again:

The followingCodeThe compiler reports an error. Do you know which statement is wrong?

Typedef char * pstr;

Char string [4] = "ABC ";

Const char * P1 = string;

Const pstr P2 = string;

P1 ++;

P2 ++;

The answer is: P2 ++ will report an error.

Const char * P1 = string indicates a pointer to the const char type ..
The P1 pointer is a variable. It can point to any char object. Even if it is not the char defined by const, P1 can point to different char objects because it is a variable. However, it indicates both the const char object and the char object. You cannot change the value that points to the object. That is to say, in the preceding example, P1 cannot modify the string. Only string values can be read.
While
Typedef char * pstr
Const pstr P2 = String This is pointed out by the pitfalls when typedef and pointer are used together.
Const pstr P2 = string
Pstr const P2 = string
Char * const P2 = string the above three statements mean one.
That is to say, P2 is a const pointer to an object of the non-const and Char Types. P2 cannot point to the second object after initialization. However, P2 can modify the string value.

For the format of defining the function pointer alias using typedef, you have never seen it before. It is necessary to take a look.

Typedef void (* sig_type) (INT); defines a function pointer sig_type. The return type of the function is void and the parameter is int.

2.Pointer. Repost an article by someone elseArticle.

Pointer is the essence of C language. It is a double-edged sword. The good and bad of pointer is the skill of the user. Next, let's take a look at the differences between pointers and arrays.

Char * P1, * P2;
Char ch [12];
Char ** pp;
P1 = CH;
Pp = & Ch;
P2 = * PP;
Check whether P1 and P2 are the same.

If the question is above, find out what is wrong.

First, array ch is not initialized. Secondly, an implicit difference is that the array name can represent the first address of the first element of the array. This is no problem. However, the array name is not a variable. After the array is allocated, the array name is fixed, and the address is also fixed. The result is that the array name cannot be processed as a variable. In the above question, pp = & Ch is obviously used as a pointer variable by using the array name, so there must be a problem.

The first question is simple and can be considered careless. But the second problem is quite complicated. extended, that is, the connection and difference between pointers and arrays in the essence of C language.

The following are two steps: first, let's take a look at the difference between pointers and arrays, and then proposeProgram.

1. Differences between pointers and Arrays

(1) pointer and array allocation

An array is a continuous memory space. The identifier of the array (that is, the array name) represents the entire array, you can use sizeof to obtain the size of the memory occupied by the Array (note that it is not the number of array elements, but the size of the memory occupied by the array, in bytes ). Example:

# Include <stdio. h>
Int main (void)
{
Char A [] = "hello ";
Int B [] = {1, 2, 3, 4, 5 };
Printf ("A: % d \ n", sizeof ());
Printf ("B memory size: % d bytes \ n", sizeof (B ));
Printf ("B elements: % d \ n", sizeof (B)/sizeof (INT ));
Return 0;
}

Array A is character type, and the strings behind it actually occupy 6 bytes (note that the end of the character string is \ 0 ). We can see from the following sizeof (B) how to obtain the inner storage space occupied by the array and how to obtain the number of elements in the array. The amount of memory space allocated by the int data type is compiler-related. By default, GCC allocates four bytes of memory for the int type.

(2) space allocation

There are two cases.

First, for global and static
Char * P = "hello ";
This defines a pointer pointing to "hello" in the rodata section, which can be put by the compiler into the string pool. The keyword in the Assembly is. ltorg. It means that the strings in the string pool can be shared, which is also a measure of Compiler optimization.
Char A [] = "hello ";
This defines an array, which is allocated to writable data blocks and will not be placed in the string pool.

Second, if it is local
Char * P = "hello ";
This defines a pointer pointing to "hello" in the rodata section, which can be put by the compiler into the string pool. The keyword in the Assembly is. ltorg. It means that the strings in the string pool can be shared, which is also a measure of Compiler optimization. In addition, the function can return its address, that is, the pointer is a local variable, but the content it points to is global.
Char A [] = "hello ";
This defines an array, which is allocated to the stack and initialized by the compiler. (In a short time, commands are directly filled in, and copied from the global string table in a long time) and will not be placed in the string pool (Similarly, it can be copied from the string pool ). Note that its address should not be returned.

(3) Usage

If it is a global pointer, it is used when no content needs to be modified, but the pointer may be modified.
If it is a global array, it is used to modify the content without modifying the address.
If you need to modify the pointer and content, define an array and then define a pointer to it.

2. My modification plan

[Armlinux @ lqm pointer] $ cat pointer. c
/*
* Copyright 2007 (C), Shandong University
* All Rights Reserved.
*
* Filename: Test. c
* Description: About pointer
* Author: Liu Qingmin
* Version: 1.0
* Date: 2007-08-27
*/
# Include <stdio. h>
/*
* Define a macro which is used to debug array mode and pointer mode.
* If 1, debug array mode; else debug pointer mode.
* You can change it according to your demo.
*/
# Define array_or_pointer 0
Int main (void)
{
Char * P1;
Char * P2;
Char ** pp;
// Test1
# If array_or_pointer
Char ch [] = "Hello, world! \ N ";
Printf ("% d, % d \ n", sizeof (P1), sizeof (P2 ),
Sizeof (PP), sizeof (CH ));
# Else
Char * Ch = "Hello, world! \ N ";
Printf ("% d, % d \ n", sizeof (P1), sizeof (P2 ),
Sizeof (PP), sizeof (CH ));
# Endif
// Test2
P1 = CH;
# If array_or_pointer
Pp = & P1;
# Else
Pp = & Ch;
# Endif
P2 = * PP;
If (p1 = P2 ){
Printf ("p1 equals to P2 \ n ");
} Else {
Printf ("p1 doesn't equal to P2 \ n ");
}
Return 0;
}

The execution result is as follows:

// When array_or_pointer is 0
[Armlinux @ lqm pointer] $./test
4, 4, 4, 4
P1 equals to p2
// When array_or_pointer is 1
[Armlinux @ lqm pointer] $./test
4, 4, 4, 15
P1 equals to p2

If the array definition method is used and PP = & Ch is used, an error similar to the following occurs:

[Armlinux @ lqm pointer] $ make
Gcc-wall-g-O2-c-o pointer. O pointer. c
Pointer. C: In function 'main ':
Pointer. C: 44: Warning: assignment from incompatible pointer type
Gcc-wall-g-O2 pointer. O-o Test
[Armlinux @ lqm pointer] $./test
4, 4, 4, 15
P1 doesn't equal to p2

Mainly, the array name type should beChar (*) [12], which is different from Char. Therefore, if you need to perform other operations on the array name, you 'd better use a pointer first.

3.Size of struct storage space

It is usually aligned by four bits. If it is less than four bits, it will be completed.

4.Function pointer

The usage of function pointers in the following programs is legal.

# Include<Iostream>
Using NamespaceSTD;
FloatF (Const Float&);
IntMain ()
{
Typedef Float(* Pfun )(Const Float&);
Pfun p1 = F;
Pfun P2 = & F;
Cout <p1 (1) <Endl;
Cout <(* P1) (1) <Endl;
Cout <P2 (1) <Endl;
Cout <(* P2) (1) <Endl;
}
FloatF (Const Float&)
{
ReturnA + 1;
}
Program output:
 
2
2
2
2

 

How to return the pointer to the function? For example, INT (* ff (INT) (int *, INT); at this point, FF is a function that has an int-type parameter and returns a pointer to the function. The Return Value of the function pointed to by the pointer is int type. An int * type and an int type parameter are accepted. This expression looks complicated and can be simplified using typedef: typedef int (* PF) (int *, INT); pf ff (INT );

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.