首页 文章

动态分配2维数组

提问于
浏览
0

有谁知道第三行“Free(array)”的作用是什么?这里的数组只是数组第一个元素的地址(换句话说,指向int * right数组中第一个元素的指针)?为什么我们需要第三行来释放2D数组的“列”?我基本上记住/理解a是一个指针,意味着保存____的地址 . 这句话是否正确?

例如:int ** a; int * b; int c; b =&c = 4; a =&b;这是对的吗?谢谢!!!

另外,一般来说,双指针基本上是动态分配数组的吗?

"Finally, when it comes time to free one of these dynamically allocated multidimensional ``arrays,'' we must remember to free each of the chunks of memory that we've allocated. (Just freeing the top-level pointer, array, wouldn't cut it; if we did, all the second-level pointers would be lost but not freed, and would waste memory.) Here's what the code might look like:" http://www.eskimo.com/~scs/cclass/int/sx9b.html

for(i = 0; i < nrows; i++)
    free(array[i]);
free(array);

2 回答

  • 0

    为什么我们需要第三行来释放2D数组的“列”?

    The number of deallocations should match up with the number of allocations.

    如果你看一下文档开头的代码:

    int **array;
    array = malloc(nrows * sizeof(int *));
    for(i = 0; i < nrows; i++) {
        array[i] = malloc(ncolumns * sizeof(int));
    }
    

    你会看到数组本身有一个 malloc() ,每行有一个 malloc() .

    释放它的代码反过来基本相同 .

    另外,一般来说,双指针基本上是动态分配的数组吗?

    不必要 . 动态分配的数组是双指针的一种用途,但它远不是唯一的用途 .

  • 2

    对malloc的调用在堆上分配内存,等于其参数指定的字节数,并返回该内存块的地址 . 你的'2D数组'实际上是一个int地址的一维数组,每个数组都指向malloc分配的一块内存 . 完成后,您需要释放每个块,使其他人可以使用 . 但是你的1D数组实际上只是另一个用于保存这些malloc地址的malloc内存块,而且还需要释放 .

    另外,当你使用printf(“%s”,array),其中array是char *时,编译器将数组视为array [0]的地址,但是将其打印出来?如果我理解它,我只是好奇 .

    是的,%s告诉printf转到你给它的任何地址(一个char的地址,也就是一个char *,让我们说),并开始阅读并显示该地址内存中的任何内容,一次一个字符,直到它找到'空字符' . 所以在字符串的情况下,这是预期的行为,因为字符串只是一个字符数组,后跟'\ 0'字符 .

相关问题