#include <stdio.h>
#include <stdlib.h>
void func(int *newvar);
int main(int argc, char *argv[])
{
int *var;
func(var);
system("pause");
return 0;
}
void func(int *newvar)
{
int *tmp = malloc(sizeof(int));
newvar = tmp;
}
After the function has exited, a value of the pointer 'var' did not change. What could be wrong in my code?
After the function has exited, a value of the pointer 'var' did not change ? if you want var to be changed then pass the address
of var
and in func()
catch with double pointer
as
int main(int argc, char *argv[]) {
int *var;
printf("before in %s : %p\n",__func__,var);
func(&var); /* pass the address of var */
printf("after in %s : %p\n",__func__,var);
//system("pause");
return 0;
}
void func(int **newvar) {
int *tmp = malloc(sizeof(*newvar));
*newvar = tmp; /* it will change the var in calling function */
printf(" in %s : %p\n",__func__,*newvar);
}
您必须像这样将var的存储位置传递给func
func(&var);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.