Key Excerpt from C language (21 ~ 24 array and pointer-top)

Source: Internet
Author: User
Tags first string

21. pointer Basics

Pointer essence: A pointer is essentially a variable that requires a certain amount of memory space. The pointer is used to save the value of the memory address.

Value Transfer and address transfer: 1. the pointer is a variable, so you can declare the pointer parameter.

2. If you need to change the value of the real parameter within a function body, you need to use the pointer parameter to transmit the address.

3. When the function is called, the real parameter value will be copied to the form parameter

4. Pointers apply to functions with complex types as parameters (reducing overhead)

Note: In C ++, you can directly use the address transfer call (FOO (& A, & B) in function parameters without a pointer. In C, you need to implement the address transfer call, only Use Pointer (FOO (* a, * B )).

Const and pointer:


22. array Basics

Array address and array name

1. the array name indicates the address of the first element of the array.

2. The address of the array needs to be obtained using the get URL &

3. The address value of the first element of the array is the same as that of the array.

4. The address of the first element of the array is different from the address of the array.

// For example: A [5], array name is A, array element first address & A [0], array address is &


Array name: 1. the array name can be regarded as a constant pointer.

2. the array name points to the starting position of the first element of the array in the memory.

3. the array name can only be used as the right value

The array name cannot be regarded as a constant pointer only in the following scenarios:

1. array name as the sizeof operator Parameter

int a[5];sizeof(a) = 20;sizeof(a+0)=4;sizeof(&a)=4;sizeof(a+1)=4;sizeof(*a) = 4;

Only when the array name is used as the sizeof parameter is the length of memory occupied by the entire array.

2. the array name is used as the & operator parameter, & A = & (a + 0 );

Common Errors: Defined as a pointer and declared as an array

#include <stdio.h>// another file// char* p = "Hello World!";extern char p[];int main(){    printf("%s\n", p);        return 0;}

The reason is: the compiler uses P to handle pointers at a time. P addresses and string addresses are separated,

When the array is not addressable, the address of array name p represents the array address.

Revised version:

#include <stdio.h>// another file// char* p = "Hello World!";extern char p[];int main(){    printf("%s\n", (char*)(*((unsigned int*)p)));        return 0;}

In this file, P is mistaken for an array, forcibly converts the type to unsigned int type pointer (unsigned int *) P, and then extracts the address represented by p * (unsigned int *) p), and then output it as a pointer.

(Char *) (* (unsigned int *) p), the result is correct.


Array summary:1. The array is a continuous memory space.

2. The address of the array and the address of the first element of the array have different meanings.

3. array names are treated as constant pointers in most cases.

4. the array name is not a pointer and cannot be confused during external declaration.


23. array and Pointer Analysis

A pointer is a special variable, and its operation rule with an integer is:

P + N; <----------> (unsigned INT) P + N * sizeof (* P );

Note: When the pointer points toArrayWhen an P-1 is created, p + 1 points to the next element of the current element.


Only the subtraction operation is supported between pointers, and the pointer types that must be involved in the operation must be the same.

P1-P2; <--------> (unsigned INT) P1-(unsigned INT) P2)/sizeof (type );

Note: 1. Only when two pointers point to the sameArrayThe pointer subtraction makes sense when it is an element in the pointer. It means the subscript difference of the element referred to by the pointer.

2. When the two pointers point to the elementNoSameArrayThe result is undefined (but can be calculated, provided that the type is the same)

Comparison of pointers: relational operations can be performed <, <=,>,> =

Note: 1. The prerequisite for pointer link operation is to point to the sameArrayElement in

2. Comparison between any two pointers (=! =) Not Limited (it can be different from the same array, because it only compares whether the addresses are equal)



Pointer form and table form access to Arrays: theoretically, pointer form is more efficient, and the optimization rate of modern compiler code has been optimized. In fixed increments, the efficiency is already quite high.


Differences between A and:

A is the address of the first element of the array.

& A is the address of the entire array

The difference between a and & A lies in Pointer operations.

A + 1 ---> (unsigned INT) A + sizeof (*)

& A + 1 ----> (unsigned INT) (& A) + sizeof (* & A) = (unsigend INT) (& A) + sizeof ()

#include <stdio.h>int main(){    int a[5] = {1, 2, 3, 4, 5};    int* p1 = (int*)(&a + 1);     int* p2 = (int*)((int)a + 1);    int* p3 = (int*)(a + 1);        printf("%d, %d, %d\n", p1[-1], p2[0], p3[1]);        return 0;}

Output: P1 [-1] <==> A [4] = 5 P2 [0] <==> 0x02000000 (Small End) p3 [1] <=> A [2] = 3

Array parameters: in C language, when an array is used as a function parameter, the compiler compiles it into a corresponding pointer.

Void F (int A []); <==> void F (int * );

Void F (int A [5]); <==> void F (int * );

Conclusion: When the defined function contains an array parameter, another parameter must be defined to indicate the size of the array.

Comparison between pointers and arrays:


1. When an array is declared, the compiler automatically allocates a continuous memory space.

2. During pointer Declaration, only four bytes of space is allocated for the pointer.

3. When used as function parameters, array parameters and pointer parameters are equivalent.

4. the array name can be considered as a constant pointer in most cases, and its value cannot be changed.

5. The essence of a pointer is a variable. The stored value is considered as the address in the memory.



Twenty-four. String in C Language

In terms of concept, there is no string data type in C language, and character arrays are used to simulate strings. Strings in C language are arrays of characters ending with '\ 0'.

Strings in C can be allocated to stack space, heap space, or read-only storage zone.

# Include <stdio. h> # include <malloc. h> int main () {char S1 [] = {'h', 'E', 'l', 'l', 'O '}; // not a string char S2 [] = {'h', 'E', 'l', 'l', 'O', '\ 0 '}; \\\ the character string char * S3 = "hello"; \\ read-only storage area char * S4 = (char *) malloc (6 * sizeof (char )); \ string S4 [0] = 'H'; S4 [1] = 'E'; S4 [2] = 'l '; s4 [3] = 'l'; S4 [4] = 'O'; S4 [5] = '\ 0'; free (S4); Return 0 ;}

String Length: refers to the number of characters contained in the string,The number of characters before the first '\ 0' character, The C language uses the '\ 0' terminator to determine the string length.

The strlen library function calculates the string length based on this standard.

#include<stdio.h>#include<string.h>char g[100];int main(){    g[0] = 'H';    g[1] = 'e';    g[2] = 'l';    g[3] = 'l';    g[4] = 'o';    g[5] = '\0';    g[6] = 'H';    g[7] = 'e';    g[8] = 'l';    g[9] = 'l';    g[10] = 'o';printf("length = %d\n",strlen(g));printf("size = %d\n",sizeof(g));return 0;}

Output: length = 5, size = 100; this is the difference between a string and a character array.

Warning about strlen: the return value of strlen is defined by the number of unsigned values. For details, it is impossible to generate a negative number (always greater than 0). The following statement is not equivalent:

char* a = "123";char* b = "1234";if(strlen(a) >= strlen(b)){  ……}if(strlen(a) - strlen(b) >= 0){  ……}

Implement strlen in one sentence:

#include <stdio.h>#include <assert.h>size_t strlen(const char* s){    return ( assert(s), (*s ? (strlen(s+1) + 1) : 0) );}int main(){    printf("%d\n", strlen( NULL));        return 0;}

Unrestricted string functions: determine the length by looking for the string Terminator '\ 0'.

String replication: char * strcpy (char * DST, const char * SRC );

String connection: char * strcat (char * DST, const char * SRC );

String comparison: int strcmp (const char * S1, const char * S2 );

Note: The input parameter must contain '\ 0 '.

Strcpy and strcat must ensure that the remaining space of the target character array is sufficient to store the entire source string.

Strcmp uses 0 to indicate that the two strings are equal. If the first string is greater than the second string, the return value is greater than 0. If the first string is smaller than the second string, the return value is less than 0.

Strcmp does not modify the parameter value. '\ 0' is the end character.

Implement the strcpy function:

# Include <stdio. h> # include <assert. h> char * strcpy (char * DST, const char * SRC) {char * ret = DST; Assert (DST & SRC ); // determine whether it is null while (* DST ++ = * SRC ++ )! = '\ 0'); return ret;} int main () {char DST [20]; printf ("% s \ n", strcpy (DST, "Delphi Tang! "); Return 0 ;}

String functions with limited length:

String replication: char * strncpy (char * DST, const char * SRC, size_t Len );

String connection: char * strncat (char * DST, const char * SRC, size_t Len );

String comparison: char * strncmp (const char * S1, const char * S2, size_t Len );

Note: strncpy: copy only Len characters to the target string

1. When the source string length is less than Len, the remaining space is filled with '\ 0.

2. When the source string length is greater than Len, only Len strings will be copied and will not end with '\ 0.

Strncat: a maximum of Len characters can be copied from the source string to the target string.

1. Always Add '\ 0' after the result string'

2. The '\ 0' is not used to fill the remaining space in the target string.

Strncmp: Compares only Len characters for Equality







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.