Search code examples
cpointersgets

Can I use a pointer as the parameter of gets in C?


I am studying the C language.

When I pass a pointer to gets(), I find it can work well.

char *ptr;
gets(ptr);
puts(ptr);

But if I define an array of pointers, it doesn't work.

char *ptr[4];
int i=0;
for(i=0;i<4;++i)
    gets(ptr[i]);
for(i=0;i<4;++i)
    puts(ptr[i]);

Are they different, or is the first part wrong in fact? I want to know the reason.


Solution

  • You pass a pointer to a function (e.g. gets()) that writes data to a memory location pointed by your pointer. In your case, you have the uninitialized pointer, which means it points to a random memory location (where applications or an operating system resides). This leads to random effects - from "working" to abnormal termination or hanging. You need to reserve memory and assign pointer to point there, e.g. by:

    char *ptr = (char*)malloc(256);
    
    gets(ptr);
    puts(ptr);
    
    free(ptr);
    

    Consider to use gets_s() that is more secure.