Array, that is, the data block)

Source: Internet
Author: User

Compiling and running environment in this article: [Mac-10.7.1 lion intel-based]

Q: sometimes it is found that the string of an array can be modified, but it cannot be modified if the string literal is used. Why?

#include <stdio.h>int main(){    char buf[] = "hello";    char *str = "hello";    buf[0] = 'a';    str[0] = 'a';    return 0;}

Code running:

In addition, it fails when running to STR [0] = 'a.

A: This is because the data in the Buf array is stored in the stack, and the string data pointed to by STR is stored in the global read-only data area. STR [0] = 'a'; modified data blocks that cannot be modified.

Q: How can I know that char * STR = "hello"; the hello string in this code is saved in the global read-only data area?

A: We can use the strings command to obtain the printable string in the executable file compiled by the code above.

Assume that the above Code is saved as char_string.c, and the compilation is gcc-O char_string char_string.c.

Let's take a look at the role of the strings program:

Use strings char_string to obtain the printable character string inside the char_string executable file:

Q: How can we prove that the data saved by the Buf in char Buf [] = "hello"; Is hello in the stack?

A: Use gcc-s char_string.c to obtain its Assembly Form:

movbL_.str(%rip), %almovb%al, -14(%rbp)movbL_.str+1(%rip), %almovb%al, -13(%rbp)movbL_.str+2(%rip), %almovb%al, -12(%rbp)movbL_.str+3(%rip), %almovb%al, -11(%rbp)movbL_.str+4(%rip), %almovb%al, -10(%rbp)movbL_.str+5(%rip), %almovb%al, -9(%rbp)leaqL_.str(%rip), %raxmovq%rax, -24(%rbp)movb$97, -14(%rbp)

Here, l _. STR is:

L_.str:.asciz "hello"

As you can see, % RBP in the assembly code above is the register corresponding to the stack base address.

Q: We often see that if arr is an array, can I be negative here if arr [I] And * (ARR + I) are the same?

A: Yes. An array is a data block. The programmer decides whether to obtain data with a higher or lower address of arr. Of course, arr indicates the initial address of the array. Getting the address lower than it may not be the programmer's intention, so be careful.

#include <stdio.h>#define PRINT_D(intValue)   printf(#intValue" is %d\n", (intValue));int main(){    int arr[] = {1, 2};    int n = 3;    PRINT_D(arr[0])    PRINT_D(arr[-1])    return 0;}

Compile and run:

As you can see, arr [0] prints the expected 1, arr [-1] Output array arr address is 4 bytes lower (the int of the author's platform is 4 bytes) integer value of the spatial data. According to the stack principle, variable N is saved in this position, so 3 is output.

Q: I often see the form of multi-dimensional arrays. I find that the form also contains the addresses of multi-dimensional array-related variables. How can I better understand them?

A: Example:

#include <stdio.h>#define PRINT_P(pointer)   printf("%10s is %p\n", #pointer, (pointer));int main (int argc, const char * argv[]){    int arr[2][3] = {1, 2, 3, 4, 5, 6};    PRINT_P(arr)    PRINT_P(&arr)    PRINT_P(arr[0])    PRINT_P(&arr[0])    PRINT_P(arr[1])    PRINT_P(&arr[1])        return 0;}

Running result:

As you can see, arr and & arr are consistent, because arr represents the address of this data; its address is still the same as it; and the virtual address of ARR can be determined at the compilation stage. Arr [0] is also an address, because arr is a two-dimensional array, so & arr [0] and ARR [0] are also consistent; arr [0] is the address of the initial data block of ARR, so they are also consistent. Likewise, it can be analyzed, arr [1] and & arr [1].

Q: sometimes it is difficult to understand the form of multi-dimensional arrays. What is the form of arrays as parameters in a simple one-dimensional array?

A: As a parameter, you only need to pass in the first address. Of course, the number of elements in the array may also be required. Shape:

#include <stdio.h>#define PRINT_P(pointer)   printf("%10s is %p\n", #pointer, (pointer));#define PRINT_D(intValue)   printf(#intValue" is %d\n", (intValue));void    print_arr(int *arr, int size){    int i = 0;    for(; i < size; ++i)        PRINT_D(arr[i])}int main (int argc, const char * argv[]){    int arr[] = {1, 2, 3};    print_arr(arr, sizeof(arr) / sizeof(arr[0]));    return 0;}

Because the array element is an integer, the array address is an integer pointer, that is, the preceding int *, and the size parameter represents the size of the array.

Q: Since the number of arrays can be expressed by sizeof (ARR)/sizeof (ARR [0]), isn't the size parameter unnecessary, can I use this expression directly in the print_arr function to obtain the array size?

A: test.

#include <stdio.h>#define PRINT_P(pointer)   printf("%10s is %p\n", #pointer, (pointer));#define PRINT_D(intValue)   printf(#intValue" is %d\n", (intValue));void    print_arr(int *arr){    int i = 0;    for(; i < sizeof(arr) / sizeof(arr[0]); ++i)        PRINT_D(arr[i])}int main (int argc, const char * argv[]){    int arr[] = {1, 2, 3};    print_arr(arr);    return 0;}

Run:

Q: Why is the number of ARR arrays incorrect?

A: Let's look at the Assembly Form of the print_arr function:

0x0000000100000dd0 <print_arr+0>:push   %rbp0x0000000100000dd1 <print_arr+1>:mov    %rsp,%rbp0x0000000100000dd4 <print_arr+4>:sub    $0x10,%rsp0x0000000100000dd8 <print_arr+8>:mov    %rdi,-0x8(%rbp)0x0000000100000ddc <print_arr+12>:movl   $0x0,-0xc(%rbp)0x0000000100000de3 <print_arr+19>:movslq -0xc(%rbp),%rax0x0000000100000de7 <print_arr+23>:cmp    $0x2,%rax0x0000000100000deb <print_arr+27>:jae    0x100000e14 <print_arr+68>0x0000000100000ded <print_arr+29>:lea    0xa4(%rip),%rdi        # 0x100000e980x0000000100000df4 <print_arr+36>:movslq -0xc(%rbp),%rax0x0000000100000df8 <print_arr+40>:mov    -0x8(%rbp),%rcx0x0000000100000dfc <print_arr+44>:mov    (%rcx,%rax,4),%esi0x0000000100000dff <print_arr+47>:mov    $0x0,%al0x0000000100000e01 <print_arr+49>:callq  0x100000e6e <dyld_stub_printf>0x0000000100000e06 <print_arr+54>:mov    %eax,-0x10(%rbp)0x0000000100000e09 <print_arr+57>:mov    -0xc(%rbp),%eax0x0000000100000e0c <print_arr+60>:add    $0x1,%eax0x0000000100000e0f <print_arr+63>:mov    %eax,-0xc(%rbp)0x0000000100000e12 <print_arr+66>:jmp    0x100000de3 <print_arr+19>0x0000000100000e14 <print_arr+68>:add    $0x10,%rsp0x0000000100000e18 <print_arr+72>:pop    %rbp0x0000000100000e19 <print_arr+73>:retq   

The CMP command at the seventh line and Jae command at the eighth line indicate that if the cyclic variable I is greater than or equal to 2, it will jump to the end point. That is to say, in this function, the size of the ARR array is regarded as 2. Why? This is because when the compiler compiles the print_arr function code, it does not know whether the input int * arr parameter is an array or a pointer. Therefore, sizeof (ARR)/sizeof (ARR [0]) the result is the value of sizeof (int *)/sizeof (INT) (2 obtained by the author's platform ). In fact, this is also a possible cause of errors when the array name is used as a parameter.

Q: If we change the parameter form int * arr to int arr [], we can regard arr as an array, and the code will be correctly executed?

A: Unfortunately, the C language syntax determines that any code will be compiled into a definite instruction. It is the same as what we mentioned above, print_arr still does not know the size of the array or pointer of the external input parameter arr. sizeof (ARR)/sizeof (ARR [0]) finally gets a strange data.

Q: What should I do?

A: You just need to input another parameter as the number of elements in the input array.

Q: I often see some strange styles about two-dimensional arrays. How can I understand them well?

A: See the following code:

#include <stdio.h>#define PRINT_P(pointer)    printf("%10s is %p\n", #pointer, (pointer));#define PRINT_D(intValue)   printf(#intValue" is %d\n", (intValue));int main (int argc, const char * argv[]){    int arr[] = {1, 2};    int (*p_arr)[2] = &arr;    PRINT_D(**p_arr)        return 0;}

Running result:

As you can see, p_arr is a pointer pointing to an array containing two integer elements. The arr array meets the requirements, so p_arr can point to it. Note that the value of p_arr is the address of ARR, so you need to unreference it when using it. * P_arr indicates the array arr, * (* p_arr) indicates * arr, that is, arr [0]. Therefore, the final output value is 1.

Q: It is too wasteful to use p_arr here. It is much easier to use arr directly than it is!

A: Yes. array pointers can be used more in two-dimensional or multi-dimensional arrays to reflect value. The following code:

#include <stdio.h>#define PRINT_P(pointer)    printf("%10s is %p\n", #pointer, (pointer));#define PRINT_D(intValue)   printf(#intValue" is %d\n", (intValue));int main (int argc, const char * argv[]){    int arr[][2] = {{1, 2}, {3, 4}};    int (*p_arr)[2] = &arr[0];    PRINT_D(p_arr[1][1])    p_arr = &arr[1];    PRINT_D(p_arr[0][1])        return 0;}

Running result:

As you can see, arr is a two-dimensional array, arr [0] is a one-dimensional array, & arr [0] is a one-dimensional array pointer, p_arr is a pointer, it needs to point to an array containing two elements, and & arr [0] exactly matches, so int (* p_arr) [2] = & arr [0]; Code OK; then, p_arr [1] indicates that p_arr points to the next array in units, that is, the array where arr [1] is located; p_arr [1] [1] is equivalent to ARR [1] [1], so the result is printed 4. I think you can analyze the intention of the last two sentences.

At the same time, you can also see that the above two sections of code, the same as int (* p_arr) [2], can point to a simple one-dimensional array, but also to a one-dimensional array in a two-dimensional array, this is the pointer, which can be indicated as long as the type is OK.

Q: Why are two-dimensional arrays and Their pointers suspended?

#include <stdio.h>#define PRINT_P(pointer)    printf("%10s is %p\n", #pointer, (pointer));#define PRINT_D(intValue)   printf(#intValue" is %d\n", (intValue));int main (int argc, const char * argv[]){    int arr[][2] = {{1, 2}, {3, 4}};    int **p_arr = (int **)arr;    PRINT_D(p_arr[0][0])        return 0;}

Running result:

A: arr is a two-dimensional array, and ARR [0] [0] is no problem; p_arr is a second-level pointer, which points to ARR, that is, the value of p_arr is arr. so p_arr [0] is the data with the address p_arr as the address, that is, the first element of the ARR array, that is, p_arr [0] is equal to 1. so p_arr [0] [0] is an integer data with the address of 1. Can this ensure that it is not suspended?

Q: sometimes it is too difficult to interpret the following statement. Is there any good method?

int (*p[3])(int *arg);int  (*(*func)(int  *p))[3];int (*(*func)[3])(int *p);

A: To Read these functions, you need to know the priority and function pointer knowledge.

One-to-one parsing:

First: (* P [3]), [] the priority is higher than *, so P is an array containing three elements. * indicates that all elements in the array are pointers. Then, the right side (int * Arg) indicates that the previous function is of the int * type, and the leftmost int indicates that the returned value is an integer. Finally, P is an array, it contains three elements, each of which is a function pointer. The format of the function pointer is: int (*) (int * Arg );

Example code:

#include <stdio.h>int (*func1)(int *arg);int (*func2)(int *arg);int (*func3)(int *arg);int main (int argc, const char * argv[]){    int (*p[3])(int *arg) = {func1, func2, func3};        return 0;}

Second: * func indicates that func is a pointer, and int * P indicates that it is a function pointer. The parameter is int * P, and an asterisk on the left indicates that the returned value is a pointer, [3] on the right indicates that the returned value is an array of three elements, each element is a pointer, And the leftmost int indicates that the returned array element is an integer. To sum up, func is a function pointer. The parameter is int * P. The returned value is an array containing five elements and a pointer.

Third: similar to the first one, but func has a pointer type. Summary: func is a pointer pointing to an array. The number of array elements is 3. Each element is a function pointer. The function pointer parameter is int * P and the return value is int.

Xichen

12:46:50

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.