Dynamically allocating array explain

前端 未结 7 1895
忘了有多久
忘了有多久 2020-12-13 11:53

This is sample code my teacher showed us about \"How to dynamically allocate an array in C?\". But I don\'t fully understand this. Here is the code:

int k;
i         


        
7条回答
  •  心在旅途
    2020-12-13 12:02

    For every type T there exists a type “pointer to T”.

    Variables can be declared as being pointers to values of various types, by means of the * type declarator. To declare a variable as a pointer, precede its name with an asterisk.

    Hence "for every type T" also applies to pointer types there exists multi-indirect pointers like char** or int*** and so on. There exists also "pointer to array" types, but they are less common than "array of pointer" (http://en.wikipedia.org/wiki/C_data_types)

    so int** test declares an array of pointers which points to "int arrays"

    in the line test = (int **)malloc(k*sizeof(int*)); puts enough memory aside for k amount of (int*)'s

    so there are k amount of pointers to, each pointing to...

    test[i] = (int*)malloc(k * sizeof(int)); (each pointer points to an array with the size of k amounts of ints)

    Summary...

    int** test; is made up of k amount of pointers each pointing to k amount of ints.

提交回复
热议问题