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

我的梦境 提交于 2020-03-16 08:07:28

问题


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.


回答1:


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.




回答2:


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.




回答3:


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]);
}


来源:https://stackoverflow.com/questions/60650328/can-i-use-a-pointer-as-the-parameter-of-gets-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!