简体   繁体   English

为指向指针数组的指针分配空间

[英]allocating space for pointer to array of pointers

Good day. 美好的一天。 I have this: MAP_ITEM **map what I think is pointer to array of pointers (correct me if I am wrong please) and I have to allocate space for it. 我有这个:MAP_ITEM **将我认为是指向指针数组的指针映射(如果我错了,请纠正我),并且我必须为其分配空间。 I can allocate space using malloc for 1 pointer, but have no idea how to do this. 我可以使用malloc为1个指针分配空间,但不知道如何执行此操作。 help would be really appreciated. 帮助将不胜感激。

Here is an example , written for use with char **, but you can modify for your purposes: 这是一个与char **结合使用的示例 ,但是您可以根据需要进行修改:

char ** allocMemory(char ** a, int numStrings, int maxStrLen)
{
    int i;
    a = calloc(sizeof(char*)*(numStrings+1), sizeof(char*));
    for(i=0;i<numStrings; i++)
    {
      a[i] = calloc(sizeof(char)*maxStrLen + 1, sizeof(char));
    }
    return a;
}    

call it like this : (for array of 10 strings, each having maximum of 79 characters (leave one for NULL term) 这样称呼它 :(对于10个字符串的数组,每个字符串最多具有79个字符(NULL项留一个)

char **arrayOfString;

arrayOfString = allocMemory(arrayOfString, 10, 80);

// //

You also need to free memory created with allocMemory 您还需要释放使用allocMemory创建的内存

void freeMemory(char ** a, int numStrings)
{
    int i;
    for(i=0;i<numStrings; i++)
        if(a[i]) free(a[i]);
    free(a);
}  

Call it like this : 这样称呼它

freeMemory(arrayOfStrings, 10);

Import the stdlib.h Then use the malloc function. 导入stdlib.h,然后使用malloc函数。 Where is an example for a one dimentional array: 一个一维数组的示例在哪里:

int* my_in_array = (int*) malloc(sizeof(int) * size_of_my_array);

Note that malloc receives the number of bytes you want to allocate, so sizeof will tell you how many bytes a datatype will need (in this case an int, but it can be used for chars, structures, ...) and then I multiplicate it by size_of_my_array, wich is the number of elements of my array. 请注意,malloc接收要分配的字节数,因此sizeof会告诉您数据类型需要多少字节(在这种情况下为int,但可以用于chars,structures等),然后乘以按size_of_my_array,它是我数组中元素的数量。

Now, just try to se this for you case. 现在,尝试为您解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM