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.
The pointer has to point somewhere first.
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:Consider to use
gets_s()
that is more secure.This is not valid C code as you did not allocate space for
ptr[i]
. On the other hand, never usegets
because it's a function that does not check for buffer limit.