I was trying to pass a character array 'p' to a function 'func' and getting it copied to another argument 'arg' inside the function. But, the array is not getting copied, though I'm able to modify the content of 'p' in the 'func' and able to verify the changes in the main function, the 'res' doesn't get copied with the values from 'p'. It prints blank. I'm not sure what mistake I'm making.
#include <stdio.h>
#include <stdlib.h>
void func(char *c, int size, char *res)
{
int i;
printf("Printing c in func...\n");
for(i=0;i<size;i++) {
printf("%c",c[i]);
}
printf("\n");
c[2] = 'j';
res = c;
}
int main(void)
{
char c[5]={'h','e','l','l','o'};
char *p,*arg;
int i, size = 5;
p=c;
arg = (char*)malloc(size);
func(p,size,arg);
printf("Printing p in main...\n");
for(i=0;i<size;i++) {
printf("%c",p[i]);
}
printf("\n");
printf("Printing arg in main...\n");
for(i=0;i<size;i++) {
printf("%c",arg[i]);
}
printf("\n");
return 0;
}
Output:
Printing c in func...
hello
Printing p in main...
hejlo
Printing arg in main...