简体   繁体   中英

If arrays are always passed call by reference then how can arrays be passed to functions like printf which are strictly call by value?

c中的数组总是通过引用传递,而printf是通过值函数调用,那么为什么我们将数组传递给printf函数以打印字符串?

First, arrays are not passed by reference in C . They decay to a pointer, which is passed by value to the function.
There is no pass by reference in C. It can only be emulated with pass by value .

We don't really pass arrays to printf : it's the aforementioned pointers we obtain through an implicit conversion (decay). This pointer can just as well be dereferenced to access the content of the array, so passing an array "by value" is not needed at all.

You don't pass arrays to printf, instead you pass the values in the array.

int arr[] = {1,2,3};
printf("%d",arr);    //Undefined behavior(garbage value)
printf("%d",arr[0]);  //will print 1

Also you can pass a pointer as an argument to a function but not a reference in C.

Edit
In case of char* which is pointer to char ,all characters in the array can be displayed till the NULL character is reached using

char* str = "Hello";
printf("%s",str);

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