使用fgets()从stdin读取

编程入门 行业动态 更新时间:2024-10-26 18:25:14
本文介绍了使用fgets()从stdin读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是C语言编程的新手,目前正在尝试使用fgets()从stdin读取一行,但是由于使用char *指向字符串I,我在内存分配方面遇到了麻烦想读.当我执行该文件时,它报告了分段错误.

I'm new to C programming and I'm currently trying to read a line from stdin using fgets(), but I'm having trouble with memory allocation since I'm using a char* to point to the string I want to read. When I execute the file it reports a segmentation fault.

这是我正在使用的功能:

This is the function I'm using:

char *read_line(char *line){ printf("%s",PROMPT); line = (char*)malloc(sizeof(char)*500); fgets(line,sizeof(line),stdin); printf("%s","pasa el fgets"); return line; }

我的主要对象:

void main(){ char line0; char *line=&line0; while(read_line(line)){ execute_line(line); } }

推荐答案

主要错误是将指针line传递给函数read_line(按值)并尝试在该函数中对其进行修改.

The main mistake is to pass the pointer line to the function read_line (by value) and try to modify it in that function.

read_line分配内存并实际创建指针值.因此它应该能够在main中更改line的值:

read_line allocates the memory and actually creates the pointer value. So it should be able to change the value of line in main:

char *read_line(char **line){ ... *line = malloc(500); fgets(*line, 500, stdin); ... return *line; } int main(void) { char *line; while(read_line(&line)){ ... } }

或者,您可以使用read_line的返回值来修改main的line.在这种情况下,您根本不需要该参数:

Or, you use the return value of read_line in order to modify main's line. In that case you don't need the parameter at all:

char *read_line(void) { char *line; ... line = malloc(500); fgets(line, 500, stdin); ... return line; } int main(void) { char *line; while(line = read_line()){ ... } }

其他错误(乔纳森·莱因哈特(Jonathon Reinhart)指出)和备注:

Additional errors (pointed out by Jonathon Reinhart) and remarks:

  • sizeof对于指针(阵列衰减到指针)不起作用.
  • 您malloc许多字符串line,但您没有free他们.
  • sizeof(char)始终为1.
  • 有些人(我也是)认为应该避免强制转换malloc的结果.
  • sizeof does not "work" for pointers (array decayed to pointers).
  • You malloc many strings line but you do not free them.
  • sizeof(char) is always 1.
  • Some people (me too) think that casting the result of malloc should be avoided.
  • 更多推荐

    使用fgets()从stdin读取

    本文发布于:2023-07-06 07:53:41,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1047547.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:fgets   stdin

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!