如何为字符串动态分配内存? [英] How to allocate memory for a String Dynamically?

查看:171
本文介绍了如何为字符串动态分配内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个文本文件和放大器读取数据;其存储有一个字符指针和放大器的结构在里面; int变量。
在从文件中读取数据,我知道会有一个字符串中获取&安培;一个整型数值。
我也知道我在哪里有开始获取位置的形式。
我不知道是该字符串的大小。
所以,我怎么能为字符串分配内存。
示例code是在这里:

 结构filevalue
{
 字符*串;
 INT整数;
}值;
fseek的(PTR,18,SEEK_SET); //从文件中的位置开始寻求从那里我得到的字符串
的fscanf(PTR,%S,value.string); // PTR是文件指针fseek的(PTR,21,SEEK_CUR); //现在从当前位置寻求
的fscanf(PTR,%D,value.integer);

在此先感谢您的帮助。


解决方案


  1. 的malloc的最大长度

  2. 阅读多到malloc分配块

  3. 揣摩出字符串的真正结束是

  4. \\ 0 到您的malloc分配块存在,因此正确地表现为一个空终止字符串(和/或过保存长度的情况下,你需要它)

  5. 可选ReAlloc如果您的块到正确的大小

或者


  1. malloc的合理猜测的 N 的为长度

  2. 读那么多

  3. 如果您找不到该缓冲区的字符串的结尾:

    1. 与成长的realloc缓冲区的 2N 的(例如),并读取下的 N 的字节到结束

    2. 转到3


  4. \\ 0 等如上


您在最大评论说。字符串的长度是有界的,所以第一个方法可能是罚款。你还没说你怎么找出其中的字符串结尾,但我假设有部分的分隔符,或者它是正确的,充满了空间,或什么的。

I am trying to read Data from a Text file & storing it inside a structure having one char pointer & an int variable. During fetching data from file I know that there will be one string to fetch & one integer value. I also know the position form where I have to start fetching. What I don't know is size of the string. So, how can I allocate memory for that String. Sample code is here :

struct filevalue
{
 char *string;
 int integer;
} value;    
fseek(ptr,18,SEEK_SET);//seeking from start of file to position from where I get String
fscanf(ptr,"%s",value.string);//ptr is file pointer

fseek(ptr,21,SEEK_CUR);//Now seeking from current position
fscanf(ptr,"%d",value.integer);

Thanks in advance for your help.

解决方案

Either

  1. malloc the maximum possible length
  2. read that much into the malloc'd block
  3. figure out where the real end of the string is
  4. write a \0 into your malloc'd block there so it behaves correctly as a nul-terminated string (and/or save the length too in case you need it)
  5. optionally realloc your block to the correct size

Or

  1. malloc a reasonable guesstimate N for the length
  2. read that much
  3. if you can't find the end of the string in that buffer:

    1. grow the buffer with realloc to 2N (for example) and read the next N bytes into the end
    2. goto 3

  4. write a \0 etc. as above


You said in a comment that the max. string length is bounded, so the first approach is probably fine. You haven't said how you figure out where the string ends, but I'm assuming there is some delimiter, or it's right-filled with spaces, or something.

这篇关于如何为字符串动态分配内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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