c++ - Why is it wrong to pass a pointer to a function taking a pointer? -
#include<iostream.h> #include<conio.h> void print(char *str){ cout<<str; } int main(){ clrscr(); char str[]="abcdef"; print(&str); getch(); return 0; } error
1. cannot convert 'char[7]' 'char *'
2.type mismatch in parameter 'str' in call print(char *)
since parameter list of function print consists of pointer, passing &str in function call should correct
also if remove '&' program runs fine (even though print function requires character reference).
since parameter list of function print consists of pointer, passing
&strin function call should correct
that's not true: not sufficient pass pointer, needs of correct type. &str pointer array, while need pointer single array element.
since arrays in c++ "decay" pointers when pass them functions, need removing ampersand:
print(str); if remove
&program runs fine (even though print function requires character reference)
that's right! array name (in case, str) implicitly converted pointer, equal pointer array's initial element. in other words, it's same writing
print(&str[0]);
Comments
Post a Comment