You need to change the initialize() function to take a pointer to your buffer and pass the address of the pointer. Although it receives the buffer that you are going to, you cannot change what buff points to this path. Just keep in mind that in this case you will have a memory leak and you won’t be able to print the contents as a string, since it does not have zero completion.
void initialize(char **buffer) { *buffer = malloc(sizeof(char)); **buffer='a'; } int main(void) { char *buff; buff = malloc(sizeof(char)); *buff = 'b'; initialize(&buff); puts("Contents of buffer are: "); printf("%c\n", *buff); return 0; }
Responses to comments below:
I don’t understand why a pointer to a pointer is needed ... does this look like a link in C ++?
When I read your code, I thought you wanted to change what the buff pointer (in main() ) points to, a new buffer. I thought that when I saw that you assigned a new buffer in your initialize() function. To be able to change the value of a variable from another location (or function), you will need the address of this variable. Since it was originally a char * character pointer, you would need a pointer to that character pointer, char ** . And yes, it looks like a C ++ link, only more verbose.
So, can I change the value of the passed variable?
If you intended to simply modify the contents of the buffer that was passed, Krtek covers this. All you had to do was discard the new buffer allocation and change what the buffer points to.
void initialize(char *buffer) { *buffer='a'; }
Regarding memory leak problem
In fact, a memory leak was caused by allocating a new buffer without freeing up previously allocated memory. You really had this:
char *buff = malloc(sizeof(char)); buff = malloc(sizeof(char));
do you mean using puts with a non-null terminating string? That is why you are using printf ("% c \ n", * buff)? making the string end with \ n?
That was another problem. puts() takes a line with a terminating zero and prints it to standard output, followed by a new line. This would not be a memory leak for printing potentially garbage text, it is just ... something else. Your buffer contained only space for one character (no null terminator). Therefore, you should not use puts() to print the contents of the buffer. You must print only one character. Using printf() with '\n' should have led to the same output behavior as puts() .