Memory allocation for char array

后端 未结 5 1319
礼貌的吻别
礼貌的吻别 2021-02-03 14:46

I have a big problem with C language when it comes to strings, char * \'s or whatever... So in this particular case I have a huge problem. I want to create an array

5条回答
  •  庸人自扰
    2021-02-03 14:58

    There are two ways of solving this issue.

    Method #1: Use a maximum size to define your array. Here's what the code looks like:

    char test[max_size];
    

    You then need to keep track of how many elements are actually used up. This is used commonly in some old-school networking code.

    Method #2: Use dynamic memory. Note that there is a bit of a performance issue here (potentially) since you have the ask the OS each time for a chunk of memory. There is an answer up here already that shows you how to do this. Just be sure to call free() once you are done using your array.

提交回复
热议问题