C Expert programming arrays and pointers are different-multidimensional arrays

Source: Internet
Author: User
Tags assert

"c Expert programming" arrays and pointers are different

tags (space delimited): Design notes

1. Background understanding 1.1 Distinguishing definitions and declarations p83
    • A declaration is tantamount to a general declaration: it does not describe itself, but rather describes objects created elsewhere, and declarations can appear multiple times;
    • A definition is equivalent to a special declaration: It allocates memory for an object and can only appear in one place.
1.2 How arrays and pointers are accessed
    • Left and right values
      ???????? X = Y;
      • The meaning of the symbol X is the address represented by X, which is called the Lvalue, and the left value is known at compile time and the left value represents the place where the result is stored.
      • The meaning of the symbol Y is the content of the address represented by Y, which is called the right value, and the right value is not known until run time , and if not specifically stated, the right value represents "Y's content".
      • Note : The array name can be used to determine the location of an object in memory and an lvalue, but it cannot be an assignment object, so the array name is an lvalue but not a modifiable lvalue.
    • How arrays and pointers are accessed
      • Array: char a[9]="abcdefgh";... c=a[i];
        The compiler symbol table has an address, 9980, run Step 1: Take the value of I, add it to 9980, run Step 2, go to the contents of the address (9980+i).
      • Pointer: char* p ... c=*p; its high-speed compiler p is a pointer (in many modern machines it is a four-byte object), and it points to an object that is a byte. In order to obtain this character, it is necessary to get the content of the address p, and take it as the address of the character and obtain the character from this address. Pointers are much more flexible to access, but additional fetches are added at a time:
        The compiler has a symbol p, its address is 4624, run step 1, take the content of address 4624, is ' 5081 '; run Step 2: Take the contents of address 5081.
2. The difference between the array and the pointer 2.1 different points:
sequence number pointer array
1 Save data address save data
2 Room Access to the data, first obtain the contents of the pointer, take it as an address, and then extract the data from this address. If the pointer has a subscript [i], the contents of the pointer and I as the address, extract data from the direct access to data, A[i] is simply a+i for the address to obtain data
3 typically used for dynamic data structures is typically used to store a fixed number of elements with the same data type
4 First off function mal LOC (), free () Hermit Assign and delete
5 usually points to anonymous data itself is the data /td>

Note! Note! Note!
Both arrays and pointers can be initialized with string constants in their definition, although they look the same, but the underlying mechanism is different.
When you define a pointer, the compiler does not allocate space for the object that the pointer points to, it simply allocates space for the pointer itself, unless it is initialized with a string constant assigned to the pointer at the same time as defined.
char *p="breadfruit";
Note that this is true only for string constants. Constants such as floating-point numbers cannot be expected to allocate space, such as:
float *pip=3.14;/*错误,无法编译通过*/
In ANSI C, the string constants created by the initialization pointers are defined as read-only (stored in the static zone). If you attempt to modify the value of this string by pointer, the program appears undefined (error)
Arrays can also be initialized with string-in constants:
char a[]="gooseberry";
As opposed to pointers, arrays initialized by string constants can be modified (stored in the stack). One of the individual characters can be changed later:
strncpy(a,"black",5);

2.2 Identical points:
    • Tips: All array names that function as arguments can always be converted to pointers by the compiler and are treated as pointers to the first element of the array .
      The compiler simply passes the address of the array to the function, not the copy of the entire array, which is actually in efficiency consideration.
      So, the form is legitimate, and eventually the compiler translates into a pointer-shaped shape:

      func(int* a);func(int a[]);func(int a[10]);

      Therefore, within the function, use sizeof (a) to not get the size of the array, because the array a[] is automatically converted to a pointer as a formal parameter, so sizeof (a) is typically 4 (space for storing pointers)

    • Access to an a[i] array in such a form is always "overwritten" by the compiler or interpreted as *(a+i) a pointer access like this.
3. Multidimensional arrays of C languages

In the C language, the only way to define and reference a multidimensional array is to use an array of arrays:

——————————————————————
char carrot[10][20];Declares a multidimensional array of 10*20
or the declaration can look more like an array of arrays form
typedef char vegetable[20];
vagetable carrot[10];

In either case, access to a single byte can be in the form of carrot[i][j],
The compiler will parse it into the form at compile time *(*(carrot+i)+j)
——————————————————————
An array of Tips:c languages is a one-dimensional array:
?? When referring to an array in C, think of it as a vector, that is, an array of objects, and the elements of an array can be another array.

# # # 3.1 layout of an in-memory array :
In the C-language array, the rightmost subscript is the first to change, and this convention is called the "Row main order". In fact, linear storage, a[i][j] 与 *(*(a+i)+j)等价
# # # 3.2 Multi-dimensional array initialization:
int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };

3.2 Declaration of a multi-dimensional array

array of pointers :
char *pea[4]; //一维指针数组,每个指针指向一个字符串,数组的每个元素内为一个char*指针
(Note the difference: char(*pea)[4];数组指针,一个指向具有4个字符类型元素的数组 )
The following can be initialized:
for (j=0;j<=4;j++)
pea[j]=malloc(6);

You can also allocate the entire array with malloc at once:
malloc(row_size*column_size*sizeof(char));
Software Creed :
For s[i][j] This form of prototype declaration:

int s[2][3];/* int 型 二维 数组**s[2]; /***s; /* 指向指针的指针*/int (*s)[3];/* 数组指针,一个指向为int数组(长度为3)的指针

This compiler acts as a pointer to the array name as an lvalue.

Jagged array:
If you declare an array of string pointers and allocate memory for those strings as needed, you will save system resources significantly:

char* turnip[UMPTEEN]char my_string[]="your message here";/*贡献字符串*/turnip[i]=&my_string[0];/*拷贝字符串*/turnip[j]=malloc(strlen(my_string)+1);strcpy(turnip[j],my_string);

tips:p225
Array and pointer parameters are modified by the compiler rule:

parameters that
are matched by an argument
Array of arrays Char C[2][3] CHAR (*) [3] Array pointers
Array of pointers Char *c[2] char** Pointer to pointers
Array pointers (row pointers) char (*A) [3] char (*A) [3] does not change
Pointer to pointers Char **a Char**a does not change
3.3 Using pointers to pass a multidimensional array to a function
    1. func(int array[10][20]);
      This approach is the simplest, but minimal, force you to handle arrays of type int of only 10 rows and 20 columns
    2. Omit the first dimension length:
      func(int array[][20]);
      But it still limits the length of each line must be 20 integers
      Similarly, it can be declared as:
      func(int (*array)[20]);Passes an array pointer with an array length of 20.
    3. func(int ** array);
      Dynamic Array form: Two-dimensional array is allocated on the heap, the address space of each row is not necessarily continuous, the function parameter uses the pointer form :
      To further improve the usability, the allocation of the two-dimensional array space is also dynamic, using malloc () to allocate space on the heap, repeating the preface in the following way:
//1. Array declarationsint**Array;Array= (int**)malloc(M *sizeof(int*)); for(i=0; i<m;i++)Array[I] = (int*)malloc(n *sizeof(int) At this time, in the scope of the allocated space, the0<=i<m,0<=j<n,ArrayI [j] Access is absolutely no problem. Well, correspondingly, function writing//2. Function DeclarationsintFuncint**Array,intMintN) {...printf("%d", *(*(Array+i) (+j)); ...} It is worth noting that, whilemalloc() Each allocated space is contiguous on the address, but multiple timesmalloc() The allocated space is not necessarily contiguous, which is fundamentally different from the two-dimensional matrix allocated on the stack, for two-dimensional arraysArray[3][3], can no longer be usedArray[1][4] to accessArray[2][1], the former address is out of bounds.
    1. Compromise: A two-dimensional array is represented by a one-dimensional array allocated on the heap, and the function arguments are in the form of pointers :
      Using a one-dimensional array to implement a two-dimensional array is a compromise scheme, but it is well understood and not easy to make mistakes. This allocates an array of space that is contiguous. It is necessary to convert two-dimensional subscript into one-dimensional subscript.
#include <stdio.h>#include <stdlib.h>#include <assert.h>intFuncint*Array,intMintN) {intI,j; for(i=0; i<m;i++) { for(j=0; j<n;j++)printf("\t%d",*(Array+I*N+J));printf("\ n"); }return 0;}intMainintargcChar* * argv) {intM,n,i;int*Array; ASSERT (argc = =3); m = atoi (argv[1]); n = atoi (argv[2]);Array= (int*)malloc(m*n*sizeof(int)); for(i=0; i<m*n;i++)Array[I] = i; FuncArray, m,n);return 0;}
    1. Newer compiler: A two-dimensional array that is allocated on the stack until execution determines size (that is, the variable-length array of C99, which allows variables to be used to define the dimensions of the array)
int quarters = 4;int regions = 5;double sales[quarters][regions]; //一个变长数组VAL

Variable-length arrays have some limitations: variable-length arrays must be auto-stored classes, meaning they must be declared inside the function or as function arguments, and cannot be initialized at the time of declaration.
C90 does not support this form, C99 support, so some newer compilers can execute on the following code. Note that the order of the parameters of print () cannot be changed.

voidPrint(int x,int y,inta[x][y]){printf("\ n");intI, J; for(i =0; I <x; i++) { for(j =0; J <y; J + +)printf("%d ", A[i][j]);printf("\ n"); }}//Function to initialize the two-dimensional arrayvoid init_2d (int *a,int x,int y){intI, J; for(i =0; I <x; i++) { for(j =0; J <y; J + +) {A[i*y+ j] = i + j; }printf("\ n"); }}intMain () {int mN scanf"%d %d",&m, &n);inta[m][n];//A dimensional whose size has beendefinedUsing Variables init_2d (A,m, n);Print(m, N, a);}

This code is derived from Http://stackoverflow.com/questions/17181577/two-dimensional-arrays-in-c.

(Updated 2013.7.28)

In addition, this allocation is still on the stack, the relevant discussion is visible in http://bbs.csdn.net/topics/90350681.

SPF 201,601,212-D arrays using tests
    1. Dynamic two-dimensional array, allocated on the heap, but with memory discontinuities
voidPrintArray (int**Array,intMintN) {if(Array= = NULL | | (*Array) = = NULL)return;printf("******** print two-dimensional array **************\n"); for(inti =0; I < m; i++) { for(intj =0; J < N; J + +)printf("%d",ArrayI [j]);printf("\ n"); }}intMain () {intM, N;printf("Please enter the rows and columns of the two-dimensional array, separated by spaces: \ n");scanf("%d%d", &m, &n);int**Array=null;//Declaration array[m][n] Two-dimensional array    Array= (int**)malloc(m*sizeof(int*));if(Array= = NULL)return-1; for(inti =0; i < M; i++) {Array[I] = (int*)malloc(nsizeof(int));if(Array[i] = = NULL)return-1; }printf("Please enter a two-dimensional array of%d rows%d columns \ n", m,n); for(inti =0; i < M; i++) for(intj =0; J < N; J + +)scanf("%d", &ArrayI    [j]); PrintArray (Array, M, N); for(inti =0; i < M; i++) { Free(Array[i]);Array[I] = NULL; } Free(Array);Array= NULL; Free(NULL); System"Pause");return 0;}
    1. Dynamic one-dimensional arrays used as two-dimensional arrays (recommended)
voidPrint (int*Array,intMintN) {if(Array= = NULL)return;printf("******** print two-dimensional array **************\n"); for(inti =0; I < m; i++) { for(intj =0; J < N; J + +)printf("%d", *(Array+I*N+J));printf("\ n"); }}intMain () {intM, N;printf("Please enter the rows and columns of the two-dimensional array, separated by spaces: \ n");scanf("%d%d", &m, &n);int*Array= (int*)malloc(m*n*sizeof(int));if(Array= = NULL)return-1;printf("Please enter a two-dimensional array of%d rows%d columns \ n", M, N); for(inti =0; i < M; i++) for(intj =0; J < N; J + +)scanf("%d",Array+I*N+J); Print (Array, M, N); Free(Array);Array= NULL; System"Pause");return 0;}
4. Reference documents:
    1. Http://www.cnblogs.com/wuyuegb2312/archive/2013/06/14/3135277.html
    2. Http://www.cnblogs.com/cpoint/p/3368380.html

C Expert programming arrays and pointers are different-multidimensional arrays

Related Article

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.