c Arrays and pointers

Source: Internet
Author: User
Tags scalar

0. Arrays and pointers are not the same

When we declare an array, we allocate some memory space to hold the array elements, but when we declare a pointer, we allocate only the memory space that holds the pointer itself.

In this respect, it is also possible to understand that sizeof is different from the array name and the pointer name.


When are arrays and pointers the same?
The C language standard does the following description
Rule 1. the array name in the expression is used by the compiler as a pointer to an element of the array
Rule 2. Subscript is always the same as the pointer and offset

Rule 3. in the declaration of a function argument (formal parameter), the array name is treated as a pointer to the first element of the array by the compiler


1. The array name is a constant pointer, not an lvalue


#include <stdio.h>

int main (int argc,char **argv)

{
int array[]={1,2,3,4};
array++;
return 0;
}

test.c|5| Error: lvalue required as increment operand

There are only two cases where the array name is not a constant pointer, that is, when the array name is the operand of sizeof and &, the former produces the total number of bytes occupied by the entire array, which produces a pointer to the array


2. Subscript Reference and indirect operation are the same


#include <stdio.h>
int main (int argc,char **argv)
{
int array[]={1,2,3,4};
int *b=array+1;
printf ("%d\n", b[1]);
printf ("%d\n", * (b+1));
printf ("%d\n", b[-1]);
printf ("%d\n", b[10]);
printf ("%d\n", 1[b]);
return 0;
}

Output
3
3
1
32595
3
This example shows a few interesting facts, B is a pointer, but B can still use subscript operator,C in handling subscript operation when the b[1] as * (b+1)
This is also why 1[b] is a legitimate cause, 1[b] is considered * (1+B), in the compiler's opinion b[1] and 1[b] there is no difference

and C language does not carry out subscript check, this is based on the belief that coder design idea, and check the subscript to consume a certain amount of resources


3. When you want to pass an array is a formal parameter can be two forms
int strlen (char *string);
int strlen (char string[]);
Even the following methods can be
int strlen (char string[100]);//The numbers inside are random


void print1 (int *a)
{
int i;
For (I=0;i < size;i++)
printf ("%d\n", A[i]);
}
void Print2 (int a[])
{
int i;
for (i=0;i< 5;i++)
printf ("%d\n", A[i]);
}
The subscript of an array is possible using variables
When invoked, the argument can only be a pointer
int a[]={1,2,3,4,5};
Print1 (a);
Print2 (a);
Print2 (&a[1]);//This is part of the array.
Arguments, even if they are not true, are valid.
int b=10;
Print2 (&AMP;B);
Actually, the pointer is passed.


This equal line implies that pointers and array names are equal, but do not be fooled by it, and the declaration is indeed equal, but only in the context of the current environment.
The difference between sizeof
char *a = "Hello";
Char b[]= {' h ', ' e ', ' l ', ' l ', ' o '};
sizeof (a) is a pointer to the memory address size, all types of pointers are the same size, is the system's word length, 32-bit system is 4 bytes, 64-bit system is 8 bytes
sizeof (b) is the number of bytes in array B, here is 5 char plus a ' + ', which is 6 bytes


Note that pointers are used here only for string constants with char *a = "Hello";
int = {*a}; Error: (twice) excess element in scalar initializer, initialization makes pointer from Interger without a cast
Char *b = {' h ', ' e ', ' l ', ' l ', ' O '};//error: (four times) excess element in scalar initializer, initialization makes pointer fro M Interger without a cast
Char *c = ' h '; Error:initialization makes pointer form Interger without a cast
Char *d = "H"; Correct

char *e = "Hello"//correct


4. Fourth is drawn from the third article
Let's talk a little bit about history
Because Char message[]={' h ', ' e ', ' l ', ' l ', ' o '}, this method of initializing character arrays is silly for comparing long character arrays, C language standard presents a fast method for initializing character arrays
Char message[]= "Hello"; Although it looks a bit like a string constant, it's not, it's just a way of initializing a list of precedents.
When a string constant is used to initialize a character array, it is an initialization list, and in any other case, he is a string constant
Note the distinction

Char message1[] = "Hello";

Message1 is the array, Message1 is also a constant pointer, can not change the direction of Message1, "Hello" is the initialization list of arrays, can be subscript or indirect operation to change the value

char *message2 = "Hello";

Message2 points to a string constant, Message2 is a pointer to a variable that can change the direction of the Message2. The value cannot be changed by subscript or indirect operation. If it's hard to change, it's compiled, but it runs wrong.


5. Pointers to arrays
int matrix[3][10];
The matrix can be thought of as a one-dimensional array that contains 3 elements, each of which is an array of 10 shaping elements (this is in the view of the computer, the matrix is a pointer to the machine, the computer does not have the concept of an array, it only knows pointers, arrays and subscript proposed to be just a convenient person to understand, This is what I have been thinking so far). (like Df-h)
Matrix: A constant pointer to its first element, so the matrix is a pointer to an array containing 10 shaping elements
Matrix+1: Still a pointer that moves backwards 4*10=40 bytes on the basis of the Matrix's address. But this is not matrix[1],maxtrix[1] equivalent to * (matrix+1), again emphasizing the subscript and the indirect operation is the same.
Matrix[0] and *matrix:maxtrix is a pointer to an array, then *maxtrix is an array that contains (*maxtrix) [0] to (*matrix) [9] So 10 elements, because the array name is the address of the first element, so * Matrix equivalent to & (*matrix) [0] is &matrix[0][0], which is a pointer to an integer.
* (* (matrix+1) +1): With the previous foundation, this is quite simple, matrix[1][1].
But it is interesting that the matrix and matrix[0] values are the same, both &matrix[0][0], in other words &matrix[0] and matrix[0] are the same (this piece I can not explain for the time being resolved later)


#include <stdio.h>
int main (int argc,char **argv)
{
int matrix[3][10]={
{1,2,3,4,5,6,7,8,9,10},
{10,9,8,7,6,5,4,3,2,1},
{5,4,3,2,1,6,7,8,9,10}
};
printf ("%p\t%p\n", matrix,matrix[0]);
printf ("%p\t%p\n", matrix+1,matrix[1]);
printf ("%p\t%p\n", matrix+2,matrix[2]);
return 0;
}

Results

0X7FFFF4609F50 0X7FFFF4609F50
0x7ffff4609f78 0x7ffff4609f78
0x7ffff4609fa0 0x7ffff4609fa0

We found that the following are more than 4*10=40 bytes of address above
So how do pointers to arrays mean?
int (*p) [10]=maxtrix;
Take a look at how to use


int a[10];
int (*PA) [Ten] = &a;
Since the value of &a and A is the same for an array, it can also be written as
int (*PA) [10]=a;//but it's going to get a warning on GCC, so don't write that well.

Although the values are the same but the types are different, this is important.


So what's the difference between int *pa=a; and int (*PA) [10]=&a;?
The value of the two PA is the same, but the type is different, or this sentence, the first PA points to an integer, the second PA points to an array, the first ++pa the step is 4, the second ++PA the step is 40
?
int a1[3];
int a2[2][3];
int (*AP) [3];
ap=&a1;
AP=A2;
It's not the same usage.
int a[10]={1,2};
Int (*PA) [10]=&a;
int *pb=a;
printf ("%p\t%p\t%p\t%p\n", pa,pb,a,&a);
printf ("%d\t%d\n", (*PA) [1],pb[1]);//Very strange, in fact, the declaration has been cleared (*PA) [10] to get a int,pa[1] compiler display is an int * type
Output:
0x7fffa745c2c0 0x7fffa745c2c0 0x7fffa745c2c0 0x7fffa745c2c0
2 2


This statement appears to be more complex than all the statements we have seen, but in fact it is not very difficult. You just have to assume that it is an expression and evaluate it. The subscript reference has a higher precedence than indirect access, but because the parentheses exist, the first is the indirect access, so p is a pointer, so what does it point to? Next is the subscript reference, so it points to an array of some type (containing 10 elements), which has no more operations, so p is a pointer to a shaped array.
So the type of matrix above is int (*) [10], and the type of matrix[0] is int *

Here's an off-topic, An array cannot be assigned to another array in its entirety, only one element can be assigned to a value.


6. Pointer array
Note the pointer to array above
int *p[10]
Subscript reference has precedence over indirect access, first performing subscript reference, So P is an array of some kind (it contains 10 elements). After a value has been obtained, an indirect access operation is performed, and the expression no longer has other operations, resulting in an int type. To summarize: An int is obtained after an element of an array is indirectly manipulated, so p is an array that contains elements that are pointers to integral types.
?
#include <stdio.h>
int main (void)
{
    const char *keyword_table[5]={
    & nbsp   ' Do ',
        ' while ',
        ' if ',
        ' else,
        "switch"
   };
    printf ("%p\t%p\t%p\t%p\t%p\t%p\t%p\t%c\n", &keyword_table,keyword_table,&keyword_table[0], & "Do", "do", Keyword_table[0],&keyword_table[0][0],*keyword_table[0]);  
    return 0;
}
Output:
0x7fff46c5f790  0x7fff46c5f790  0x7fff46c5f790  0x4006ac         0x4006ac       &NBSP;0X4006AC       &NBSP;0X4006AC        d

C Arrays and pointers

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.