我可以使用指针作为C语言中的gets参数吗? [英] Can I use a pointer as the parameter of gets in C?

查看:665
本文介绍了我可以使用指针作为C语言中的gets参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习C语言.

当我将指针传递给gets()时,我发现它可以很好地工作.

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.

推荐答案

您将指针传递给函数(例如gets()),该函数将数据写入指针所指向的存储位置.在您的情况下,您具有 uninitialized 指针,这意味着它指向随机的内存位置(应用程序或操作系统所在的位置).这会导致随机效应-从工作"到异常终止或挂起.您需要保留内存并分配指向该内存的指针,例如通过:

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

考虑使用更安全的gets_s().

这篇关于我可以使用指针作为C语言中的gets参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆