void func(char *ptr) //Passed by reference
{
*ptr = 'B';
}
int main()
{
char *ptr;
ptr = (char *) malloc(sizeof(char) * 1);
*ptr = 'A';
printf("%c\n", *ptr);
func(ptr);
printf("%c\n", *ptr);
}
I was confuse I know that ptr=(char*)malloc (sizeof(char*1)
here means allocate 1 byte and return a pointer to the allocation then assign to ptr
, so ptr
is a pointer.
But when it calls func(ptr)
why it not use &
? Although what I want is to change the character inside ptr
points to? Why not using void func(char** ptr)
and send func(&ptr)
here? Is it possible?
I mean what made this pass by reference?
second code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *c=NULL;
test(c);
printf("after test string is %s\n",c);
return 0;
}
void test (char *a)
{
a=(char*)malloc(sizeof(char)*6);
a="test";
printf("inside test string is %s\n",a);
}