How to allocate memory for a String Dynamically?

前端 未结 4 1231
梦谈多话
梦谈多话 2021-01-26 15:30

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 wil

4条回答
  •  无人及你
    2021-01-26 16:11

    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.

提交回复
热议问题