Hi all ,
I am experimenting with writing functions with pointers as arguments. There are 2 functions below,one takes a pointer to integer and changes the integer value, the other takes a pointer to char and tries to change the string.The first one works, but the seconds does not although they are same.Whats the problem ?
In the first one, your function receives a copy of a pointer to some integer; when you ask to change the value of the integer it points to, that integer is changed.
In the second, your function receives a copy of a pointer to a character. You then take that pointer, and you are not changing the thing it points to. You are making a whole new string, not changing the original one, and setting your pointer name (which is a copy of the pointer in the main function) to point at that instead. When your function chgStr returns , the copy of the pointer that the function had is destroyed, the original pointer has not been touched, and the string the original pointer pointed to has also not been touched.
webJose :
How can I do it being it C ? how can I call your chgStr() function in above code ?
Moschops :
I understand your point on that when function returns its space and variables are destroyed.But this is why I am sending a pointer,so the original place that pointer is pointing to is filled with a new thing(newName). How is this wrong ?
My second choice is the C way of doing it. See the difference? That difference between my function and your function is the answer to the question you asked Moschops.
Let me see if I can illustrate:
typedefchar *LPSTR;
Do you understand this line? I am just giving the name LPSTR to char*. You know that C strings are just arrays of char's, right? This means that, in general, you can roughly say that a pointer to the first char in the string is "the string", so we will be thinking about LPSTR as the C string data type.
By using the above data type, let's redefine your function:
void chgStr(LPSTR name);
If I were asked to explain this function prototype, I would say "It is a function with no return value that takes a C string in its first parameter". I do not say "takes a C string BY VALUE..." because in C everything is by value.
If you take the above + what Moschops explains, the issue should be clear now: You passed a copy of the C string. You need to pass a pointer to the C string in order to change the original C string. This leads us to the following function prototype: