简短的回答:writeLocation是一个局部变量,是cryptedPointer. 修改writeLocation时,cryptedPointer不修改。
如果要修改cryptedPointer,则必须将指针传递给它,如下所示:
#include <stdio.h>
int pointeeChanger(char** writeLocation) { /* Note: char** */
*writeLocation = "something"; /* Note: *writeLocation */
return 0;
}
int main(void)
{
char crypted[] = "nothing";
char* cryptedPointer = crypted;
pointeeChanger(&cryptedPointer); /* Note: &cryptedPointer */
printf("The new value is: %s", cryptedPointer);
return 0;
}
但是,此代码还有其他问题。调用后pointeeChanger(),cryptedPointer不再指向crypted数组。我怀疑您实际上想更改该数组的内容。此代码无法做到这一点。
要更改您的值,crypted[]您需要使用strcpy()or (preferably) strncpy()。此外,您将需要注意crypted[]数组的大小 -"something"长度大于"nothing"并将导致缓冲区溢出,除非crypted[]将其做得更大。
此代码将修改原始crypted[]数组:
#include <stdio.h>
#include <string.h>
#define MAX_STR_LEN 64
/*
* Only char* required because we are not modifying the
* original pointer passed in - we are modifying what it
* points to.
*/
int pointeeChanger(char* writeLocation)
{
/*
* In C, you need to use a function like strcpy or strncpy to overwrite a
* string with another string. Prefer strncpy because it allows you to
* specify a maximum size to copy, which helps to prevent buffer overruns.
*/
strncpy(writeLocation, "something", MAX_STR_LEN);
/* strncpy doesn't automatically add a \0 */
writeLocation[MAX_STR_LEN] = '\0';
return 0;
}
int main(void)
{
/*
* The +1 is because an extra character is required for the
* null terminator ('\0')
*/
char crypted[MAX_STR_LEN + 1] = "nothing";
pointeeChanger(crypted);
printf("The new value is: %s", crypted);
return 0;
}