简体   繁体   中英

How to create new variable in function using address

When I create a new array using main array's base address I write this:

main()
{
    int a[]={0,1,2,3,4,5,6,7,8,9};
    display(a);
}

display(int anew[])
{
    int i;
    for(i=0;i<10;i++)
        printf("%d ",anew[i]);
}

Why can I not do the same when trying to create a new int variable using address like this?

main()
{
    int a=7;
    display(&a);
}

display(int b)
{
    printf("%d ",b);
}

Because display(int anew[]) is the same as display(int *anew) but display(int *b) is not the same as display(int b) . In C, when passed in a function, an array 'degenerates' into a pointer (to the first element). No such thing happens with an integer (only arrays and functions).

With the line below you're passing the address of a to the display function. This will not work because display(int b) is expecting a parameter of type int .

display(&a); // should be replaced by display(a)

If you want to print the value of a in the display function by sending its address you should do the following:

main()
{
    int a=7;
    display(&a); //Pass the address of variable a
}

display(int *b) //Is expecting an address as argument
{
    printf("%d ", *b); //Print the value at that address
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM