0
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void getName(char *ptr)
{
    char *str = "Hello World";
    ptr = (char*)malloc(strlen(str)+1);
    for(int i =0; str[i] != '\0'; i++)
    {
        ptr[i] = str[i];
    }
}

int main()
{
    char *ptr = NULL;
    getName(ptr);
    printf("String: %s\n", ptr);
    return 0;
}

I have a null char pointer in main function. I am passing that pointer to a function and coping a local string into pointer. I am getting output on console as null. Can anyone explain what is the reason?

Sanket Joshi
  • 139
  • 17
  • You should *return* the pointer to the newly allocated buffer to the `main` function. Also don't forget to put terminating null-character to the buffer. – MikeCAT Mar 31 '22 at 11:17

0 Answers0