本文介绍了输入动态分配字符串的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我知道它听起来像是一个新手问题,但我从来没有真的不得不这么打扰b ,我甚至没有在clc中找到答案 常见问题 我想知道在 数组中输入字符串的真正方法是什么'动态分配。我的意思是,我希望不要看到任何像char mystring [100]这样的东西。我不想看到任何数字 (如果可能的话)我只想声明像char * mystring;并且 然后我不知道如何从stdin中获得如此多的字符(当然是\\ / 0的 空间)。 我真的想知道一次是什么才是最聪明的方式来从stdin输入字符串并以某种方式存储它们他们只需要 所需的空间,我不想在我的代码中看到任何数字,例如100或 10,000甚至4,294,967,296。有什么方法可以做到吗?I know it must sound like a newbie question, but I never really had tobother with that before, and I didn''t even find an answer in the c.l.cFAQI''d like to know what''s the really proper way for input a string in anarray of char that''s dynamically allocated. I mean, I wish not to seeany such things as char mystring[100]; I don''t want to see any number(if possible) I just want to declare something like char *mystring; andthen I don''t know how allocate it with just as many chars (with thespace for the \0 of course) as you get from stdin.I''d really like to know once for all what''s the smartest way ofinputing strings from stdin and storing them in a way so they take justthe needed space and I don''t want to see any number such as 100 or10,000 or even 4,294,967,296 in my code. Any way it can be done?推荐答案 一个常见的习语如下: #include< stdio.h> #include< stdlib.h> ; void * frealloc(void * ptr,size_t sz) { void * tmp; if((tmp = realloc(ptr,sz))!= NULL) return(tmp); free(ptr); return(NULL); } char * getline(FILE * f) { char * str = NULL; size_t sz = 0; int ch; for(size_t len = 0 ;; ++ len){ ch = fgetc(f); if(ch == EOF&&!len) return(NULL); if(len == sz) str = frealloc(str,sz = sz * 2 + 1); if(ch == EOF || ch ==''\ n''){ str [len] =''\ 0''; 返回(str); }否则{ str [len] = ch; } } } 然而,平均而言,大约25%的已分配内存将被浪费。 你可以通过替换 返回(str); 与 返回(frealloc(str,len + 1)); 但是你可能仍然会失去相当多的堆碎片, 取决于你的系统的malloc()实现的好坏。 br $> DES - Dag-Erling Sm?rgrav - de *@des.no 让我们假设你读完了''\ n'' - 终止的行, fgets()的方式,但没有明确的长度限制。你好b / b 可以做这样的事情(伪代码,没有错误检查): buffer =< empty> do { 使用realloc扩展缓冲区() 附加下一个输入字符 } while(字符不是'\\'n'') ; 使用realloc扩展缓冲区() 追加''\ 0'' 为了效率,你为了效率'd可能想要避免相当多的进出内存分配器的行程,所以一个改进 将从一个更宽敞的缓冲区开始并扩展更多比如必要的时候一个角色。 (我自己做的功能 这个 - 每个人最终写一个 - 从100个字符开始 并且每次需要时加上缓冲区当前大小的一半扩展: 100,150,225,...) 一旦你读完整行你就可以了,如果你愿意的话,realloc( ) 缓冲区最后一次修剪到精确的大小。我发现 很少值得打扰:你的程序可能会花费很多时间来处理行和free()或者很快就重新使用缓冲区。 br /> - Eric Sosman es*****@acm-dot-org.inva 盖子Let''s suppose you''re reading complete ''\n''-terminated lines,the way fgets() does but with no explicit length limit. Youcould do something like this (pseudocode, no error checking):buffer = <empty>do {expand buffer with realloc()append next input character} while (character wasn''t ''\n'');expand buffer with realloc()append ''\0''For efficiency''s sake you''d probably want to avoid quiteso many trips in and out of the memory allocator, so a refinementwould be to start with a roomier buffer and expand by more thanone character at a time if necessary. (My own function for doingthis -- everybody writes one eventually -- begins with 100 charactersand adds half the buffer''s current size each time it needs to expand:100, 150, 225, ...)Once you''ve read the entire line you can, if you like, realloc()the buffer one final time to trim it to the exact size. I findthat''s seldom worth the bother: your program is probably going toprocess the line and free() or re-use the buffer pretty soon.--Eric Sosman es*****@acm-dot-org.invalid 来临时存储字符串: #include< stdlib.h> #include< stdio.h> #include< string.h> #define BUFFER_SIZE 100 int main(){ char buffer [BUFFER_SIZE]; char * inputString = NULL; size_t inLen = 0; while(fgets(缓冲区,BUFFER_SIZE,stdin)!= NULL){ inLen + = strlen(缓冲区); if (inputString == NULL){ inputString = malloc(inLen); inputString [0] =''\'''; } else { inputString = realloc(inputString,inLen); } if(inputString == NULL){ / * malloc或realloc失败* / 退出(-1); } strcat(inputString,buffer); / *检查换行符* / if(inputString [inLen-1] ==''\ n''){ 这里 / *流程输入* / / *然后记得释放inputString * / free(inputString); inputString = NULL; } } }to temporarily store the string:#include <stdlib.h>#include <stdio.h>#include <string.h>#define BUFFER_SIZE 100int main () {char buffer[BUFFER_SIZE];char *inputString = NULL;size_t inLen = 0;while (fgets(buffer, BUFFER_SIZE, stdin) != NULL) {inLen += strlen(buffer);if (inputString == NULL) {inputString = malloc(inLen);inputString[0] = ''\0'';} else {inputString = realloc(inputString, inLen);}if (inputString == NULL) {/* malloc or realloc failed */exit(-1);}strcat(inputString, buffer);/* check for newline */if(inputString[inLen-1] == ''\n'') {/* process input here *//* then remember to free inputString */free(inputString);inputString = NULL;}}} 这篇关于输入动态分配字符串的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 09:34