In-depth understanding of the C-pointer IV: Pointers and arrays

Source: Internet
Author: User

Arrays are the basic data structures built into C, which are closely related to array notation and pointer notation. A common mistake to recognize is that arrays and pointers are completely interchangeable, although array names can sometimes be used as pointers, but the names of arrays are not pointers. One of the differences between arrays and pointers is that although the name of an array can return an array address, the name cannot be the target of an assignment operation.

Overview

An array is a contiguous collection of homogeneous elements that can be accessed with an index. The elements of an array are contiguous in memory, and the elements are of the same type. The length of the array is fixed, and the REALLOC function and variable-length array provide techniques for dealing with arrays that require varying lengths.

A one-dimensional array is a linear structure that accesses members with an index. Depending on the different memory models, the length of the array may be different.

int vector[5];

the name of the array refers only to a piece of memory, and the sizeof operator is used to get the number of bytes allocated for the array. To know the number of elements of an array, simply divide it by the length of the element.

int vector[5];p rintf ("Vector is%p\nsize is%d\n", &vector, sizeof (vector));//vector was 0xbffb8c08//size is 20

You can initialize a one-dimensional array with a single block statement.

int vector[5] = {1,2,3,4,5};

declares a two-dimensional array. You can use a two-dimensional array as an array of arrays, using only one subscript to access a two-dimensional array to get a pointer to the corresponding row.

int Matrix[2][3] = {{1,2,3},{4,5,6}};p rintf ("0 is%p\n1 are%p\n", &matrix[0], &matrix[1]);//0 is 0XBF984044//1 0xbf984050

as you can see, two addresses are exactly 12 bytes, which is the length of the matrix array row.

Assigns the array address to the pointer.

int* PV = vector;

Note that this notation and &vector[0] are equivalent, unlike &vector, which is a pointer to the entire array returned. One is an array pointer, one is an integer pointer, and the pointer type is different. PV actually represents an address, * (Pv+i) is written equivalent to Pv[i], the former is called the pointer notation , the latter is called array notation .

printf ("Pv[0" is%d\n* (pv+1) was%d\n ", PV[0],*PV);//pv[0] is 1//* (pv+1) is 1

The PV pointer contains the address of a block of memory, the square bracket notation takes out the address contained in the PV, adds the index I with the pointer arithmetic operator, and then returns the contents of the new address. Adding an integer to the pointer actually adds an integer to the length of the data type, which also applies to the array name, * (pv+1) and * (vector+1) are equivalent. The array notation can therefore be interpreted as an "offset and extract" operation. Vector[i] and * (VECTOR+I) The results are the same, only slightly different in implementation, can be ignored. Note that pointers can be left-valued, but array names cannot be used as lvalue, and vector=vector+1 is an incorrect notation.

one-dimensional arrays

If you allocate memory from the heap and assign the address to a pointer, you can definitely use the subscript for the pointer and treat the memory as an array. The length of an existing array created with malloc can be adjusted by the ReAlloc function. C99 supports variable-length arrays, but variable-length arrays can only be declared inside functions. So if the life cycle of the array needs to be longer than the function, or if you are not using C99, then you can only use ReAlloc.

The following function accepts the user's input and uses the REALLOC function to dynamically request the required memory and press ENTER to end the input.

char* getLine (void) {const size_t sizeincrement = 10;char* buffer = malloc (sizeincrement); char* currentposition = Buffer;s ize_t maximumlength = sizeincrement;size_t length = 0;int character;if (currentposition = = null) {return null;} while (1) {character = fgetc (stdin); if (character = = ' \ n ') {break;} if (++length >= maximumlength) {maximumlength + = sizeincrement;char* Newbuffer = realloc (buffer,maximumlength); if ( Newbuffer = = null) {free (buffer); return NULL;} CurrentPosition = Newbuffer + (currentposition-buffer); buffer = Newbuffer;} *currentposition++ = character;} *currentposition = ';p rintf ("Buffer is%s\n", buffer); return buffer;} GetLine ();

passing a one-dimensional array as an argument to a function is actually the address of the array passed by value, we need to tell the length of the function array, otherwise the function has only one address and does not know how long the array is. For a string, you can rely on the NUL character to determine its length. For some arrays it is not possible to judge.

Declares a pointer to an array and a pointer array, and the array pointer is different. A pointer to an array is a pointer to an array of elements labeled 0, an array of pointers to an array of elements, and a pointer to an array type.

int vector[2] = {1,2};int* PV1 = vector;//pointer to an array int* pv2[2];//pointer array, you can use a loop to assign a memory int (*PV3) [2];//array type pointer to each pointer

Now let's make a distinction between array notation and pointer representation in an array of pointers.

int* array[5];array[0] = (int*) malloc (sizeof (int)), *array[0] = 100;* (array+1) = (int*) malloc (sizeof (int)); * * (ARRAY+1) = 200;

here Array[1] and * (array+1) are equivalent, are actually pointer types, use the malloc function to allocate memory on the heap for pointers, and to extract pointers to assign values to the data, so * * (array+1) is not difficult to understand, a * solution to a pointer, The pointer is then interpreted to get the data, and the [] parentheses have been explained before, which is equivalent to a fetch address and indexed operations. Of course, you can also use array[0][0] instead of *array[0].

pointers and multidimensional arrays

You can consider a subset of a multidimensional array as a sub-array, such as each row of a two-dimensional array as a one-dimensional array. The array is stored in row-column order, and the memory address of the first element of the second row is immediately following the last element in the first row.

int Matrix[2][3] = {{1,2,3},{4,5,6}};int (*pmat) [3] = MATRIX;//3 is the number of columns in a two-dimensional array printf ("Size of pmat[0] is%d\n", sizeof (Pmat[0]) );//size of Pmat[0] is 12

As you can see, the length of the first element of the array pointer is 12 bytes, that is, the length of the first line. If you want to access the first element of the first row, you need to use pmat[0][0] to access it. Array[i][j] equals array+i*sizeof (row) + j* sizeof (element). sizeof (row) is the total size of a row, and sizeof (element) is the size of a single element, and the address of array is array[0][0].

When passing array parameters to a function, consider how to pass the number of dimensions of the array and the size of each dimension. The following are two ways to pass a two-dimensional array:

void Display2darray (int arr[][3], int rows) {}void display2darray (int (*arr) [3], int rows) {}

the number of rows is specified in two methods. If you pass an array dimension that exceeds two dimensions, you need to specify the length of the other dimension in addition to the one-dimensional part. If you pass an array of array3d[3][2][4]:

void Display3darray (int (*arr) [2][4], int rows) {}

When using malloc to allocate memory for different sub-arrays of two-dimensional arrays, it is possible to cause memory allocation discontinuities. Using block statements for one-time initialization does not have this problem. There are two strategies for allocating contiguous memory to a two-dimensional array using malloc. Suppose a two-dimensional array has three rows and four columns. The first one-time allocation of all memory 3*4*sizeof (element) is then used to manually calculate the memory address to be accessed using the method previously mentioned in how to access array[i][j]. The second method is divided into two steps. The first step is to use malloc to allocate a piece of memory to hold a pointer to a pointer to each row of a two-dimensional array. The second step is to assign all of the memory to the pointer of Array[0][0], and then calculate the position of the array[1][0] and array[2][0], assigning the two key pointers respectively, so that the subscript can be accessed based on the pointer of each line.

int rows = 3;int columns = 5;//The first method int* Matrixx = (int*) malloc (Rows * columns * sizeof (int));//The second method int **matrixy = (in t**) malloc (rows * sizeof (int*)); matrixy[0] = (int*) malloc (Rows * columns * sizeof (int)); int i = 1;while (i<rows) {i++ ; Matrixy[i] = matrix[0] + i * columns;}

An irregular array is a two-dimensional array with a different number of columns per row. You can use compound literals to initialize an irregular array.

(const int) {100} (int [3]) {10, 20, 30}

access and maintenance of irregular arrays are cumbersome and should be considered carefully before use.

In-depth understanding of the C-pointer IV: Pointers and arrays

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.