c/c++语言开发共享C – 在函数中使用fgets()从stdin读取行

我试图用stgets()从stdin读取行,我想在我的函数中使用fgets(),我认为这是问题所在。 字符串最长可达1024个字符。 当我运行此代码时,我得到“Segmentation fault(core dumped)”

#include  #include  #include  #define MAX_SIZE 1025 void print_fgets(); int main() { print_select(); return 0; } void print_select() { char *str; int length; while (fgets( str, MAX_SIZE, stdin)!=NULL) { length=strlen(str); if (length==MAX_SIZE-1 && str[length-1]!='n') { printf("Error, line overeached buffer!n"); return 1; } if (str[length-1]=='n') str[length-1]=''; printf("%sn", str); } } 

    问题是您尝试写入str指针指向的位置。 最初它会指向一些垃圾地址(由于char *str没有被初始化)。

    您可以尝试通过更改以下基于堆栈的解决方案:

     /* This is just a pointer */ char *str; 

    至:

     /* This is a character array (on the stack) of size MAX_SIZE, initialized to zero */ char str[MAX_SIZE] = {0}; 

    或者,如果要为数组动态分配内存,请执行以下操作:

     char *str; str = calloc(1, MAX_SIZE); if (str == NULL) { /* Failed to allocate memory */ } ... Your code free(str); /* You should always free dynamically allocated memory when you are done with it */ str = NULL; /* It's a good practice to point your pointer to NULL after it's free'd */ 

    不要忘记数组索引从0开始并转到MAX_SIZE - 1 (在您的情况下)和NUL终止(字符串必须以它结束)。

     #include  #include  #include  #define MAX_SIZE 1025 int print_select(); /* Use correct name (instead of print_fgets()) */ int main() { print_select(); return 0; } int print_select() /* Fix. Dhould return int if you have a return  statement. */ { char str[MAX_SIZE]; /* Initialize static memory. */ int length; while (fgets( str, MAX_SIZE, stdin)!=NULL) { length=strlen(str); if (length==MAX_SIZE-1 && str[length-1]!='n') { printf("Error, line overeached buffer!n"); return 1; } if (str[length-1]=='n') { str[length-1]=''; } printf("%sn", str); } return 0; /* Function may not be returning an int. Return it in those cases. */ } 

      以上就是c/c++开发分享C – 在函数中使用fgets()从stdin读取行相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/519306.html

      (0)
      上一篇 2020年12月5日
      下一篇 2020年12月5日

      精彩推荐