pointer to char not working

I want to print the txt[5]="abcd". However, it doesnot work. I am not good in pointer understanding. Would anyone kind to guide me in this regard?


void f(char *c) {

char txt[5]="abcd";

c=txt;
printf("function: %s\n",c);
}

int main(void)
{

char *str = (char *)malloc(5);
f(str);
printf("main: %s\n",str);
free(str);

return 0;
}


The output is some random ASCII characters.
The line c = txt; introduces a memory leak. It means the original value of c is lost and the memory allocated in main() can never be freed.
When function f() ends, the local array txt[5] is destroyed and c now points to an invalid address. Don't return the address of a local variable.

Use strcpy to copy the characters (not the address) from txt to the block of memory pointed to by c.
1
2
3
4
5
6
7
8
void f(char *c) {

    char txt[5]="abcd";
	
//	c=txt;
    strcpy(c, txt);
    printf("function: %s\n",c);
}

Thank you Chervil!

Now I understand what was the problem!
The line c = txt; introduces a memory leak

Does it? The 'c' is just a copy of 'str'. A by value argument. The str is not modified by function call.
Thanks keskiverto, yes you're right.
Last edited on
Topic archived. No new replies allowed.