Search code examples
cstringpointersvoiddynamic-allocation

How to read a string into a void pointer?


I have been trying to read an input as string from the user inside a void pointer in C. SO i wrote something like the following:

void *ptr;
ptr = calloc(100,sizeof(char));
printf("Enter the string: ");
fgets(*((char *)ptr),100,stdin);
printf("You entered ");
puts(*((char *)ptr));

I know I may not be doing it the right way, so can anybody please help me show the right way of taking a string input in a void pointer? I want something as

input:- Enter the string: welcome user

output:- You entered: welcome user


Solution

  • Just convert the void* to a char*:

    void *ptr;
    ptr = calloc(100,sizeof(char));
    printf("Enter the string: ");
    fgets((char*)ptr,100,stdin);
    printf("You entered ");
    puts((char*)ptr);
    

    fgets and puts take a pointer as first argument, so you could use (char*)ptr to convert the pointer.

    If you write *((char*)ptr) you treat the void pointer as a char pointer, but also dereference it with * which will give you the first character. This is not what you want here.