使用指针符号从C中的键盘获取输入字符串? [英] Taking input string from keyboard in C using pointer notation?

查看:101
本文介绍了使用指针符号从C中的键盘获取输入字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从键盘输入字符串.当我尝试此操作无效时.

I am trying to take in string from keyboard. When I tried this it didn't work.

char *s;
fgets(s,80, stdin);

当我尝试使用上面的代码时,我遇到了分段错误.但是,当我使用下面的代码时,它可以工作,并且不会出现分段错误.

I get a segmentation fault when I am trying to use the above code. However when I use below code it works, and I don't get a segmentation fault.

char s[81];
fgets(s, 80, stdin);

为什么在尝试使用指针( char * s )存储字符串时出现分段错误?

Why do I segmentation fault when I try to store the string using pointer (char *s)?

推荐答案

这是因为当您这样做

char *s;

在这个时间点 s 具有垃圾值,指向无效的地址.取消引用将导致不确定的行为,在您遇到分段错误的情况下.

at this point of time s has garbage value, pointing to an invalid address. Dereferencing it will lead to undefined behaviour, in your case you get segmentation fault.

您需要先使用malloc分配一些内存.

You need to allocate some memory first using malloc.

s = malloc (sizeof (char) * 81);
fgets (s, 80, stdin);

而且,在使用完内存后,请务必记住使用

And, after you are done with the memory, always remember to free it using

free (s);

这将帮助您在较大的程序中出现明显的内存泄漏.

This will help you obvious memory leakage in larger programs.

这篇关于使用指针符号从C中的键盘获取输入字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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