Hee guys,
I have been reading a couple of things about pointers and pointees and started getting curious. The only thing I dont understand is how pointers behave in functions, hence the following code:
#include <stdio.h>
int pointeeChanger(char* writeLocation) {
writeLocation = "something";
return 0;
}
int main(void)
{
char crypted[] = "nothing";
char* cryptedPointer = crypted;
pointeeChanger(cryptedPointer);
printf("The new value is: %s", cryptedPointer);
return 0;
}
What my intention to do is to adjust the pointee, “crypted” var, through a pointer given to a function. The only thing is that it is not working. Could you please explain me what is going wrong in my thought process. I am fairly new to C so my errors could be fairly basic.
Thanks in advance!
Greetings,
Kipt Scriddy
Short answer:
writeLocationis a local variable and is a copy ofcryptedPointer. When you modifywriteLocation,cryptedPointeris not modified.If you want to modify
cryptedPointer, you have to pass a pointer to it, like so:There are other issues with this code though. After the call to
pointeeChanger(),cryptedPointerno longer points to thecryptedarray. I suspect you actually wanted to change the contents of that array. This code fails to do that.To change the value of
crypted[]you will need to usestrcpy()or (preferably)strncpy(). Also you will need to watch the size of thecrypted[]array –"something"is longer than"nothing"and will cause a buffer overflow unlesscrypted[]is made larger.This code will modify the original
crypted[]array: