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

2020-04-19 08:26发布

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.

标签: c pointers gets
3条回答
家丑人穷心不美
2楼-- · 2020-04-19 08:55

The pointer has to point somewhere first.

#define BUFSIZE 100

char *ptr = malloc(BUFSIZE);
fgets(stdin, ptr, BUFSIZE);
puts(ptr);

char *ptr[4];
int i=0;
for(i=0;i<4;++i) {
    ptr[i] = malloc(BUFSIZE);
    fgets(ptr[i], BUFSIZE, stdin);
}
for(i=0;i<4;++i) {
    puts(ptr[i]);
}
查看更多
劳资没心,怎么记你
3楼-- · 2020-04-19 09:02

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.

查看更多
The star\"
4楼-- · 2020-04-19 09:03
char *ptr[4];
int i=0;
for(i=0;i<4;++i)
    gets(ptr[i]);

This is not valid C code as you did not allocate space for ptr[i]. On the other hand, never use gets because it's a function that does not check for buffer limit.

查看更多
登录 后发表回答