Similarities and differences between arrays and pointers through a practical example

前端 未结 5 1792
时光取名叫无心
时光取名叫无心 2020-12-05 15:56

Given the following code:

#include 
#include 

int main()
{
    int a[1];
    int * b = malloc(sizeof(int));

    /* 1 */
             


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 16:40

    In your case what is happening is that you are passing both variables a and b with the & operator to the scanf function. What this operator does is "ask" the memory address of the variable and pass that address to the scanf function. But, as both of your variables are pointers, what they have indeed is an memory address, so when you pass &a or &b you are passing the memory of the pointer, not the memory address that it holds.

    Example:

    int x;
    int *ptr;
    
    x = 10;
    

    suppose the memory address of x is 1000. You are storing the number 10 at the memory address 1000. Now you do this:

    ptr = &x;
    

    You are storing the address 1000 in the pointer. But 1000, apart being an address, is a number itself, so the pointer, as does x, still needs a memory address to store that information. Suppose the pointer memory location is 1004. Now look the example:

    *ptr == 10;  //x content
    ptr == 1000 //x memory address
    &ptr == 1004 // ptr memory address. 
    

    So if you want to pass to scanf the variable x, but using the pointer, you need to pass the x address stored in it

    scanf("%d", ptr);
    

    Just to ilustrate another example of pointers and vectors

    int main
    {
        int vet[5];
        int *ptr;
    
        ptr = vet;
    
        for(int i = 0; i < 5; ++i)
        {
            scanf("%d", (ptr+i) );
        }
    }
    

    Here you can read the vector using the pointer. Also, using pointer arithmetics you can iterate over the memory addresses of the vector.

提交回复
热议问题