KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I passed a pointer ptr to a function whose prototype takes it as const . foo( const char *str ); Which according to my understanding means that it will not be able to change the contents of ptr passed. Like in the case of foo( const int i ) . If foo() tries to chnage the value of i , compiler gives error. But here I see that it can change the contents of ptr easily. Please have a look at the following code foo( const char *str ) { strcpy( str, "ABC" ) ; printf( "%s(): %s\n" , __func__ , str ) ; } main() { char ptr[ ] = "Its just to fill the space" ; printf( "%s(): %s\n" , __func__ , ptr ) ; foo( const ptr ) ; printf( "%s(): %s\n" , __func__ , ptr ) ; return; } On compilation, I only get a warning, no error: warning: passing argument 1 of ‘strcpy’ discards qualifiers from pointer target type and when I run it, I get an output instead of Segmentation Fault main(): Its just to fill the space foo(): ABC main(): ABC Now, my questions is 1- What does const char *str in prototype actually means? Does this mean that function cannot change the contents of str ? If that is so then how come the above program changes the value? 2- How can I make sure that the contents of the pointer I have passed will not be changed? From "contents of the pointer" in the above stated question, I mean "contents of the memory pointed at by the pointer", not "address contained in the pointer". Edit Most replies say that this is because of strcpy and C implicit type conversion. But now I tried this foo( const char *str )
Tags (comma-separated)
Save Edits
Cancel