In C, everything is passed by value.
What you are passing to fun() is a copy of the pointer you have in main().
That means the copy of ptr is aimed at the allocated memory, and that memory set to 115.
The ptr in main() still points at an undefined location because it has never been assigned.
Try passing a pointer to the pointer, so that within fun()
you have access to the pointer itself:
#include <stdio.h>
#include <stdlib.h>
int* fun(int**); // <<-- CHANGE
int main()
{
int a=5;
int* ptr;
// ptr=(int*)malloc(sizeof(int));
fun(&ptr); // <<-- CHANGE
a=*ptr;
printf("\n the val of a is:%d",a);
return 0;
}
int* fun(int** another_ptr) // <<-- CHANGE
{
*another_ptr = (int*)malloc(sizeof(int)); // <<-- CHANGE
**another_ptr = 115; // <<-- CHANGE
return *another_ptr;
}
The other option would be to make fun()
actually return the updated pointer (as advertised), and assign this to ptr:
#include <stdio.h>
#include <stdlib.h>
int* fun(int*);
int main()
{
int a=5;
int* ptr;
// ptr=(int*)malloc(sizeof(int));
ptr = fun(ptr); // <<-- CHANGE
a=*ptr;
printf("\n the val of a is:%d",a);
return 0;
}
int* fun(int* another_ptr)
{
another_ptr = (int*)malloc(sizeof(int));
*another_ptr = 115;
return another_ptr; // <<-- CHANGE
}
Edit: I renamed the variable in fun()
to make it clear that it is different from the one you use in main()
. Same name doesn't mean anything here.
The fun()
function parameter is a copy of the variable you passed into fun()
. So when you do:
ptr = (int*)malloc(sizeof(int));
*ptr = 115;
you only change that copy. You should change the function signature:
int* fun(int** ptr)
{
*ptr = (int*)malloc(sizeof(int));
**ptr = 115;
}
and change how you call it accordingly.
You need to pass the address of the pointer in main if you want to change it:
fun(&ptr);
(and change fun
appropriately, of course)
At the moment, it's changing the local variable ptr
inside the function, and of course that change doesn't magically appear anywhere else.
You are confused about several things here, but one easy way of writing the function is:
int * fun()
{
int * ptr = (int*)malloc(sizeof(int));
* ptr = 115;
return ptr;
}
You are now responsible for freeing the memory, so in main():
int * ip = fun();
printf( "%d", * ip );
free( ip );
The alternative is to pass the address of apointer (a pointer to a pointer) to the function:
void fun( int ** pp )
{
* pp = (int*)malloc(sizeof(int));
** pp = 115;
}
then your code in main() looks like:
int * ip;
fun( & ip );
printf( "%d", * ip );
free( ip );
I think you can see that the first function is simpler to use.
Вы передаете ptr
по значению в fun
. fun
получит копию ptr
, которая будет изменена. Вам нужно передать ptr
как int **
.
void fun(int** ptr)
{
*ptr = (int*)malloc(sizeof(int));
**ptr = 115;
}
и вызвать его с помощью:
fun(&ptr);
(Я также удалил возвращаемое значение из fun
, поскольку оно не использовался)
Переменная int * ptr
передается по значению функции fun
. Таким образом, значение, присвоенное ptr
внутри функции с использованием ptr = (int *) malloc (sizeof (int));
, не будет отражено вне функции. Итак, когда вы выполняете a = * ptr;
в main ()
, вы пытаетесь использовать неинициализированный указатель. Если вы хотите отразить изменения, внесенные в ptr вне функции, вам нужно изменить сигнатуру fun на fun (int ** ptr)
и сделать * ptr = (int *) malloc (sizeof (int));
Помните, что если вы хотите, чтобы функция изменяла значение аргумента, вы должны передать указатель на этот аргумент. Это относится к значениям указателя; если вы хотите, чтобы функция изменяла значение указателя (а не то, на что указывает указатель), вы должны передать указатель на этот указатель:
void fun (int **ptr)
{
/**
* Do not cast the result of malloc() unless you are
* working with a *very* old compiler (pre-C89).
* Doing so will supress a valuable warning if you
* forget to include stdlib.h or otherwise don't have
* a prototype for malloc in scope.
*
* Also, use the sizeof operator on the item you're
* allocating, rather than a type expression; if you
* change the base type of ptr (say from int to long),
* then you don't have to change all the corresponding
* malloc() calls as well.
*
* type of ptr = int **
* type of *ptr = int *
* type of **ptr = int
*/
*ptr = malloc(sizeof **ptr);
*ptr = 115;
}
int main(void)
{
int *p;
fun(&p);
printf("Integer value stored at %p is %d\n", (void *) p, *p);
return 0;
}
Кстати, в вашем примере имеется несоответствие типов; ваше первоначальное объявление fun
возвращает int *
, но определение возвращает void.