void fun(char arr[]){
cout<<arr;//successfully received and printed
}
main(){
char *ptr="hello";
fun(ptr);
/*
char arr2[]=ptr; throws error....initialiser fails to determine size of arr2
*/
getch();
}`
Why am I allowed to pass a char pointer and receive it in array,but can not directly assign char pointer to array.As far I know,assignment takes place implicitly when we pass parameters to a function.So why is this difference in behavior?
The declaration
void fun(char arr[]){
is equivalent to
void fun(char *arr){
which means that, in this case, no need of size of character array to be passed to the function. Now arr
points to the same location as of ptr
. But in case of
char arr2[] = ptr;
compiler doesn't know about the size of ptr
as it is a pointer to first character of string literal hello
and hence the compiler fails out to determine the size for array arr2
and it throws the error. You must have to specify the size of array.
The size of character array can be omitted only with the initializer like;
char arr2[] = "Hello World";
In this case compiler determines the size of array arr2
from the size of string Hello World
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With