Memory allocation for char array

后端 未结 5 1313
礼貌的吻别
礼貌的吻别 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:49

    Depending upon your (i) tool-chain and (ii) how and when you will know you the size - you have the option to use either (a) Variable Length Arrays or (b) Dynamic Memory Allocation functions.

    if (tool-chain supports C99 and later) or (you will know the array length at runtime) use Variable Length Array

    if (older tool-chain) or (you want the flexibility of allocating and releasing the memory) use Dynamic Memory allocation function

    here are samples

    1 Variable Length Array

    void f(int m, char C[m][m])
    {
        char test[m];
        :
    }
    

    or

    2 using Dynamic Memory Allocation function

    void somefunc(int n)
    {
        char *test;
    
        test = malloc (n * sizeof (char));
    
        // check for test != null
    
        // use test
    
        free (test);
    }
    

    can be written using VLA as

    int n = 5;
    char test[n];
    

提交回复
热议问题