I use malloc to dynamically allocate memory, use memset to initialize the 2D array, and use free to free the memory. The code is:
int n1=2,n2=5;
int in1;
float **a;
a = (float **)malloc(n1*sizeof(float *));
for (in1=0;in1<n1;in1++)
a[in1] = (float *)malloc(n2*sizeof(float));
memset(a[0],0,n1*n2*sizeof(float));
free(*a);free(a);
First problem when I run the code is:
* Error in `./try1': free(): invalid next size (fast): 0x0000000000c06030 *
Second question is: since the prerequisite for using memset is having contiguous memory. That's why it doesn't work on 3D array (see Error in memset() a 3D array). But here a is a 2D pointer or array, the input of memset is a[0]. My understanding is:
+---------+---------+-----+--------------+
| a[0][0] | a[0][1] | ... | a[0][n2 - 1] |
+---------+---------+-----+--------------+
^
|
+------+------+-----+-----------+
| a[0] | a[1] | ... | a[n1 - 1] |
+------+------+-----+-----------+
|
v
+---------+---------+-----+--------------+
| a[1][0] | a[1][1] | ... | a[1][n2 - 1] |
+---------+---------+-----+--------------+
The above figure shows the contiguous memory. So memset(a[0],0,n1*n2*sizeof(float)); can successfully initialize **a. Am I right? If it's not contiguous, how can the initialization be successful? (it is from the tested open source code)
The above figure shows the contiguous memory.
No it doesn't. It shows two regions of contiguous memory: a[0][0] -> a[0][n2 - 1] and a[1][0] -> a[1][n2 - 1].
You could try to initialize and erase each of them:
int n1 = 2, n2 = 5;
int in1;
float **a;
a = (float **)malloc(n1*sizeof(float *));
for (in1 = 0; in1<n1; in1++)
{
a[in1] = (float *)malloc(n2*sizeof(float));
memset(a[in1], 0, n2*sizeof(float));
}
for (in1 = 0; in1<n1; in1++)
{
free(*(a+in1));
}
free(a);
Only in the case of a 'real' 2d array, like float a[2][5];, your assumption about contiguous memory is correct.
Related
The below code is pointer to "array of pointers" code. I am not sure that this is correct.
tags[0][0] = malloc(sizeof(char)*5);
strcpy(tags[0][0],"hi");
tags[0][1] = malloc(sizeof(char)*5);
strcpy(tags[0][1],"h2");
Can anyone please tell are the above lines correct in following code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char *(*tags)[2] = malloc (2 * sizeof *tags);
tags[0][0] = malloc(sizeof(char)*5);
strcpy(tags[0][0],"hi");
tags[0][1] = malloc(sizeof(char)*5);
strcpy(tags[0][1],"h2");
tags[1][0] = "<head";
tags[1][1] = "</head>";
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++)
printf (" %s", tags[i][j]);
putchar ('\n');
}
free (tags);
}
Is there any difference between the above and array of pointers to pointers?
Yes, the code principle is absolutely correct. It's the correct way to do dynamic allocation of a 2D array.
This
char *(*tags)[2]
means that tags is a pointer to an array of 2 char pointers.
So when you do
char *(*tags)[2] = malloc (2 * sizeof *tags);
you allocate an array of two arrays of two char pointers. It's equivalent to:
char* tags[2][2];
when not using dynamic allocation.
So yes, the code is fine. That's exactly the way to do it. And you should always do like that when you want a dynamic 2D array.
However, your code lacks:
free(tags[0][0]);
free(tags[0][1]);
BTW: Storing both pointers to dynamic allocated memory and pointers to string literals in the same array is a bit "strange" and can be problematic as you need to track which pointers to free and which not to free.
This looks ok to me. I haven't seen pointers like this very much in practice, but I would describe tags as "A pointer to a 2-size array of character pointers". When you malloc (2 * sizeof *tags);, you create space for two of of these 2-size array of character pointers. This is what you have from each line:
char *(*tags)[2] = malloc (2 * sizeof *tags);
tags -----> [char*][char*] // index 0 of tags
[char*][char*] // index 1 of tags
// You now have 4 character pointers in contiguous memory that don't
// point to anything. tags points to index 0, tags+1 points to index 1.
// Each +1 on *(tags) advances the pointer 16 bytes on my machine (the size
// of two 8-byte pointers).
Next malloc:
tags[0][0] = malloc(sizeof(char)*5);
+-------> 5 bytes
|
tags ------> [char*][char*] // index 0
^
index 0 of tags[0], this now points to 5 bytes
After first strcpy
strcpy(tags[0][0],"hi");
+-------> {'h', 'i', '\0', <2 more> }
|
tags ------> [char*][char*] // index 0
Next malloc
tags[0][1] = malloc(sizeof(char)*5);
+-------> 5 bytes
|
tags ------> [char*][char*] // index 0
^
index 1 of tags[0], this now points to 5 bytes
Next strcpy
strcpy(tags[0][1],"h2");
+-------> {'h', '2', '\0', <2 more> }
|
tags ------> [char*][char*] // index 0
And finally, the string literal assignments
tags[1][0] = "<head";
tags[1][1] = "</head>";
tags -----> [char*][char*] // index 0 of tags
[char*][char*] // index 1 of tags
| |
| |------> points to string literal "</head>"
|--------------> points to string literal "<head"
If you really want to clean up properly, you should
free(tags[0][1]);
free(tags[0][0]);
// the order of the above doesn't really matter, I just get in the
// habit of cleaning up in the reverse order that I malloced in.
// But if you free(tags) first, you've created a memory leak, as
// there's now no existing pointers to tags[0][0] or [0][1].
free(tags);
Of course, all memory gets reclaimed by the OS as soon as the process exits anyway.
What you want to achieve is array of strings.
char ***tags = malloc(sizeof(char**) * numberofpointers);
for (int i = 0; i < numberofpointers; ++i)
{
tags[i] = malloc(sizeof(char*) * numberofstringsperpointer);
}
for (int i = 0; i < numberofpointers; ++i)
{
for (int j = 0; j < numberofstringsperpointer; ++j)
{
tags[i][j] = malloc(sizeof(char) * (numberofcharacterperstring + 1));
}
}
strcpy(tags[0][0], string)
I was wondering, why does this work
// read n as matrix dimension, then:
int* M;
M = (int*)malloc(n * n * sizeof(int));
// cycle through each "cell" in the matrix and read a number with
scanf("%d", &M[i * n + j]);
and this doesn't?
// read n as matrix dimension, then:
int** M;
M = malloc(n * n * sizeof(int));
// cycle through each "cell" in the matrix and read a number with
scanf ("%d", &M[i][j]);
I just don't get it. In both cases they should be double pointers, am I right?
int ** is supposed to point to an int*. Here you have allocated some memory - to be precise sizeof(int)*rows*cols bytes and then you use M[i] etc. Here M[i] which is basically *(M+i) we will access i*sizeof(int*) offset from the one address returned by malloc but you allocated for rows*cols int's not int*-s - so you will eventually access memory that you shouldn't (typically on a system where sizeof(int*) > sizeof(int)) which will lead you to undefined behavior.
What is the solution then? Well allocate for int*-s.
int ** M = malloc(sizeof *M * rows);
if(!M){
perror("malloc");
exit(EXIT_FAILURE);
}
for(size_t i = 0; i < rows; i++){
M[i] = malloc(sizeof *M[i] * cols);
if(!M[i]){
perror("malloc");
exit(EXIT_FAILURE);
}
}
For your case rows = N and cols = N.
This will you give you a jagged array which you can access like you did. With malloc comes the responsibility of checking the return type of it and freeing the memory when you are done working with it. Do that.
On the first case you are accessing the allocated chunk of memory and you have realized the memory access using indices i and j to give yourself a flavor of accessing memory that you do in case of 2d array. So there is no point using double pointer here. It is legal what you did.
In both cases they should be double pointers
No they shouldn't be. The first one is different than the second one. They are not in anyway indicating the same thing.
Case 1 :-
int* M;
M = (int*)malloc(n * n * sizeof(int));
Here memory is allocated for M which is single pointer. Let's say you want to store 5 integers into that memory. So it looks like
-------------------------------
| 10 | 20 | 30 | 40 | 50 |
-------------------------------
M M[0] M[1] M[2] m[3] M[4] <--- Its a 1D array, only one row of 5 int
Case 2 :-
int **M;
M = malloc(n * n * sizeof(int));
M[0][0] M[0][1]
| | | | ....... | | <---- If below one is not done then how will you store the numbers into these
----------- ----- ---------
| | | |
M[0] M[1] M[2] .... M[4] <--- didn't allocated memory for these rows or 1D array
| | | |
-----------------------------------
|
M <---- allocated memory for this
It doesn't work because M is double pointer and you allocated memory only for M, you didn't allocated memory for M[row]. thats why below statement didn't work.
scanf ("%d", &M[i][j]);
So to make it work first Allocate the memory for M as you did
M = malloc(row*sizeof(*M)); /* row indicates no of rows */
and then allocate for each row
for(int index = 0 ;index < row;index++) {
M[index] = malloc(col * sizeof(*M[index])); /* col indicates number of columns */
}
And scan the matrix input
for(int index = 0 ;index < row;index++) {
for(int sub_index = 0 ;sub_index < col; sub_index++)
scanf("%d",&M[index][sub_index]);
}
and once work is done with matrix free the dynamically allocated memory using free() for each row to avoid memory leakage.
The other answers (suggesting one malloc for M and n mallocs for the rows) are correct, but not the most efficient way to allocate a matrix. You can, however, allocate the matrix with only one malloc call, while still allowing you to index it by row and column with M[i][j], as follows:
int (*M)[cols] = malloc(rows * sizeof *M);
This declares M as a pointer to array of int with length cols and requests malloc to allocate rows number of such arrays, meaning you get a single block of rows * cols ints (sizeof *M == sizeof(int) * cols).
When the malloc succeeds, you can use M as if it were declared as int M[rows][cols] so you can read into it with
scanf("%d", &M[i][j]);
It looks more complicated, but allocates M as one contiguous block of memory, which allows the processor to optimize access to it.
And as an added bonus you can also free it with just one call:
free(M);
This does require C99 support, or at least support for variable-length arrays, but the matrix itself is not a proper variable-length array. It is still allocated by malloc, but the declaration of M allows you to use it like one.
A question ask me if this code, contains any error.
The compiler doesn't give me any errors but this code contains some arguments that I don't know
The code is this:
int* mycalloc(int n) {
int *p = malloc(n*sizeof(int)), *q; //what does the ", *q"?
for (q=p; q<=p+n; ++q) *q = 0;
return p;
}
The possible solutions are:
The program is correct
There is an error at line 1
There is an error at line 2
There is an error at line 3
There is an error at line 4
There is no compile time error in the above code but at run time it will crash because of q<=p+n. q is simply an integer pointer.
It should be
for (q=p; q<p+n; ++q) /** it works even though n is zero or you can add seperate if condition for the same, this may be the interviewer concern **/
*q = 0;
What mymalloc is doing is allocating space for n integers and initialize
them with 0.
This could have been done so:
int *mymalloc(size_t n)
{
int *arr = malloc(n * sizeof *arr);
if(arr == NULL)
return NULL;
memset(arr, 0, n * sizeof *arr);
return arr;
}
or better
int *mymalloc(size_t n)
{
return calloc(n, sizeof int);
}
The way your function is doing this, is by looping through the array using a
pointer q. Let me explain
int *p = malloc(n*sizeof(int)), *q;
It declares two int* (pointers to int) variables p and q. p is
initialized with the values returned by malloc and q is left uninitialized.
It's the same as doing:
int *p;
int *q;
p = malloc(n*sizeof(int));
but in one line.
The next part is the interesting one:
for (q=p; q<p+n; ++q)
*q = 0;
First I corrected the condition and wrote it in two lines.
You can read this loop as follows:
initialize q with the same value as p, i.e. p and q point to the start
of the allocated memory
end the loop when q is pointing beyond the allocated memory
at the end of the loop, do ++q, which makes q go to the next int
In the loop do *q = 0, equivalent to q[0] = 0, thus setting the integer to
0 that is pointed to by q.
Let us think about the memory layout. Let's say n = 5. In my graphic ?
represents an unkown value.
BEFORE THE LOOP
b = the start of the allocated memory aka malloc return value
si = size of an integer in bytes, mostly 4
(beyond the limits)
b+0 b+1*si b+2*si b+3*si b+4*si b+5*si
+---------+---------+---------+---------+---------+
| ???? | ???? | ???? | ???? | ???? |
+---------+---------+---------+---------+---------+
^
|
p
In the first loop, q is set to p and *q = 0 is executed. It's the same as
doing p[0] = 0.
FIRST ITERATION
b = the start of the allocated memory aka malloc return value
si = size of an integer in bytes, mostly 4
(beyond the limits)
b+0 b+1*si b+2*si b+3*si b+4*si b+5*si
+---------+---------+---------+---------+---------+
| 0 | ???? | ???? | ???? | ???? |
+---------+---------+---------+---------+---------+
^
|
p,q
This is how the memory would look like after *q=0. Then the next loop is
executed, but before of that q++ is executed
BEFORE SECOND ITERATION, `q++`
b = the start of the allocated memory aka malloc return value
si = size of an integer in bytes, mostly 4
(beyond the limits)
b+0 b+1*si b+2*si b+3*si b+4*si b+5*si
+---------+---------+---------+---------+---------+
| 0 | ???? | ???? | ???? | ???? |
+---------+---------+---------+---------+---------+
^ ^
| |
p q
Now *q = 0 is executed, which is the same as p[1] = 0:
SECOND ITERATION,
b = the start of the allocated memory aka malloc return value
si = size of an integer in bytes, mostly 4
(beyond the limits)
b+0 b+1*si b+2*si b+3*si b+4*si b+5*si
+---------+---------+---------+---------+---------+
| 0 | 0 | ???? | ???? | ???? |
+---------+---------+---------+---------+---------+
^ ^
| |
p q
Then the loop continues, and you get now the point. This is why in your code the
condition of the loop q <= p+n is wrong, because it would do 1 step farther
than it needs and would write a 0 beyond the limits.
You loop is using pointer arithmetic. Pointer arithmetic is similar to regular
arithmetic (i.e. addition, subtraction with natural numbers), but it takes
the size of the object in consideration.
Consider this code
int p[] = { 1, 2, 3, 4, 5};
int *q = p;
p is an array of int of dimension 5. The common size of int is 4, that
means that the array q needs 20 bytes of memory. The first 4 bytes are for
p[0], the next 4 for p[1], etc. q is a pointer to int pointing at the
first element of the array p. In fact this code is equivalent to
int p[] = { 1, 2, 3, 4, 5};
int *q = &(p[0]);
That is what people call array decay, meaning that you can access the array as
if where a pointer. For pointer arithmetic there is almost no distinction
between the two.
What is pointer arithmetic then?
This: p+2. This will get you a pointer that is 2 spaces after p. Note that
I'm using the word space and not byte, and that's because depending on the type
of p, the number of bytes will be different. Mathematically what the compiler
is doing is calculating the address from
address where p is pointing + 2x(number of bytes for an int)
because the compiler knows the type of the pointer.
That's why you can also have expressions like p++ when p is a pointer. It is
doing p = p + 1 which is p = &(p[1]);.
b is the base address where the memory starts
memory
address b+0 b+1*si b+2*si b+3*si b+4*si
+---------+---------+---------+---------+---------+
| 1 | 2 | 3 | 4 | 5 |
+---------+---------+---------+---------+---------+
p p+1 p+2 p+3 p+4
pointer
(pointer arithmetic)
import cv2
import numpy as np
import scipy.ndimage
from sklearn.externals import joblib
from tools import *
#from ml import *
import argparse
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import confusion_matrix
from sklearn.externals import joblib
from sklearn import svm
import numpy as np
import os
import cv2
parser = argparse.ArgumentParser()
parser.add_argument('--mode', '-mode', help="Mode : train or predict", type=str)
parser.add_argument('--a', '-algorithm', help="algorithm/model name", type=str)
parser.add_argument('--i', '-image', help="licence plate to read", type=str)
parser.add_argument('--model', '-model', help="Model file path", type=str)
#parser.add_argument('--d', '-dataset', help="dataset folder path", type=str)
EDIT: Sorry guys, I forgot to mention that this is coded in VS2013.
I have a globally declared struct:
typedef struct data //Struct for storing search & sort run-time statistics.
{
int **a_collision;
} data;
data data1;
I then allocate my memory:
data1.a_collision = (int**)malloc(sizeof(int)*2); //Declaring outer array size - value/key index.
for (int i = 0; i < HASH_TABLE_SIZE; i++)
data1.a_collision[i] = (int*)malloc(sizeof(int)*HASH_TABLE_SIZE); //Declaring inner array size.
I then initialize all the elements:
//Initializing 2D collision data array.
for (int i = 0; i < 2; i++)
for (int j = 0; j < HASH_TABLE_SIZE; j++)
data1.a_collision[i][j] = NULL;
And lastly, I wish to free the memory (which FAILS). I have unsuccessfully tried following some of the answers given on SO already.
free(data1.a_collision);
for (int i = 0; i < HASH_TABLE_SIZE; i++)
free(data1.a_collision[i]);
A heap corruption detected error is given at the first free statement. Any suggestions?
There are multiple mistakes in your code. logically wrong how to allocate memory for two dimension array as well as some typos.
From comment in your code "outer array size - value/key index" it looks like you wants to allocate memory for "2 * HASH_TABLE_SIZE" size 2D array, whereas from your code in for loop breaking condition "i < HASH_TABLE_SIZE;" it seems you wants to create an array of size "HASH_TABLE_SIZE * 2".
Allocate memory:
Lets I assume you wants to allocate memory for "2 * HASH_TABLE_SIZE", you can apply same concept for different dimensions.
The dimension "2 * HASH_TABLE_SIZE" means two rows and HASH_TABLE_SIZE columns. Correct allocation steps for this would be as follows:
step-1: First create an array of int pointers of lenght equals to number of rows.
data1.a_collision = malloc(2 * sizeof(int*));
// 2 rows ^ ^ you are missing `*`
this will create an array of int pointers (int*) of two size, In your code in outer-array allocation you have allocated memory for two int objects as 2 * sizeof(int) whereas you need memory to store addresses. total memory bytes you need to allocate should be 2 * sizeof(int*) (this is poor typo mistake).
You can picture above allocation as:
343 347
+----+----+
data1.a_collision---►| ? | ? |
+----+----+
? - means garbage value, malloc don't initialize allocate memory
It has allocated two memory cells each can store address of int
In picture I have assumed that size of int* is 4 bytes.
Additionally, you should notice I didn't typecast returned address from malloc function because it is implicitly typecast void* is generic and can be assigned to any other types of pointer type (in fact in C we should avoid typecasting you should read more from Do I cast the result of malloc?).
Now step -2: Allocate memory for each rows as an array of length number of columns you need in array that is = HASH_TABLE_SIZE. So you need loop for number of rows(not for HASH_TABLE_SIZE) to allocate array for each rows, as below:
for(int i = 0; i < 2; i++)
// ^^^^ notice
data1.a_collision[i] = malloc(HASH_TABLE_SIZE * sizeof(int));
// ^^^^^
Now in each rows you are going to store int for array of ints of length HASH_TABLE_SIZE you need memory bytes = HASH_TABLE_SIZE * sizeof(int). You can picture it as:
Diagram
data1.a_collision = 342
|
▼ 201 205 209 213
+--------+ +-----+-----+-----+-----+
343 | | | ? | ? | ? | ? | //for i = 0
| |-------| +-----+-----+-----+-----+
| 201 | +-----------▲
+--------+ 502 506 510 514
| | +-----+-----+-----+-----+
347 | | | ? | ? | ? | ? | //for i = 1
| 502 |-------| +-----+-----+-----+-----+
+--------+ +-----------▲
data1.a_collision[0] = 201
data1.a_collision[1] = 502
In picture I assuming HASH_TABLE_SIZE = 4 and size of int= 4 bytes, note address's valuea
Now these are correct allocation steps.
Deallocate memory:
Other then allocation your deallocation steps are wrong!
Remember once you have called free on some pointer you can't access that pointer ( pr memory via other pointer also), doing this calls undefined behavior—it is an illegal memory instruction that can be detected at runtime that may causes—a segmentation fault as well or Heap Corruption Detected.
Correct deallocation steps are reverse of allocation as below:
for(int i = 0; i < 2; i++)
free(data1.a_collision[i]); // free memory for each rows
free(data1.a_collision); //free for address of rows.
Further more this is one way to allocate memory for two dimension array something like you were trying to do. But there is better way to allocate memory for complete 2D array continuously for this you should read "Allocate memory 2d array in function C" (to this linked answer I have also given links how to allocate memory for 3D arrays).
Here is a start:
Your "outer array" has space for two integers, not two pointers to integer.
Is HASH_TABLE_SIZE equal to 2? Otherwise, your first for loop will write outside the array you just allocated.
There are several issues :
The first allocation is not correct, you should alloc an array of (int *) :
#define DIM_I 2
#define DIM_J HASH_TABLE_SIZE
data1.a_collision = (int**)malloc(sizeof(int*)*DIM_I);
The second one is not correct any more :
for (int i = 0; i < DIM_I; i++)
data1.a_collision[i] = (int*)malloc(sizeof(int)*DIM_J);
When you free memory, you have to free in LastInFirstOut order:
for (int i = 0; i < DIM_I; i++)
free(data1.a_collision[i]);
free(data1.a_collision);
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;
int** test;
printf("Enter a value for k: ");
scanf("%d", &k);
test = (int **)malloc(k * sizeof(int*));
for (i = 0; i < k; i++) {
test[i] = (int*)malloc(k * sizeof(int)); //Initialize all the values
}
I thought in C, to define an array you had to put the [] after the name, so what exactly is int** test; isn't it just a pointer to a pointer? And the malloc() line is also really confusing me.....
According to declaration int** test; , test is pointer to pointer, and the code pice allocating memory for a matrix of int values dynamically using malloc function.
Statement:
test = (int **)malloc(k * sizeof(int*));
// ^^------^^-------
// allocate for k int* values
Allocate continue memory for k pointers to int (int*). So suppose if k = 4 then you gets something like:
temp 343 347 351 355
+----+ +----+----+----+----+
|343 |---►| ? | ? | ? | ? |
+----+ +----+----+----+----+
I am assuming addresses are of four bytes and ? means garbage values.
temp variable assigned returned address by malloc, malloc allocates continues memory blocks of size = k * sizeof(int**) that is in my example = 16 bytes.
In the for loop you allocate memory for k int and assign returned address to temp[i] (location of previously allocated array).
test[i] = (int*)malloc(k * sizeof(int)); //Initialize all the values
// ^^-----^^----------
// allocate for k int values
Note: the expression temp[i] == *(temp + i). So in for loop in each iterations you allocate memory for an array of k int values that looks something like below:
First malloc For loop
--------------- ------------------
temp
+-----+
| 343 |--+
+-----+ |
▼ 201 205 209 213
+--------+ +-----+-----+-----+-----+
343 | |= *(temp + 0) | ? | ? | ? | ? | //for i = 0
|temp[0] |-------| +-----+-----+-----+-----+
| 201 | +-----------▲
+--------+ 502 506 510 514
| | +-----+-----+-----+-----+
347 |temp[1] |= *(temp + 1) | ? | ? | ? | ? | //for i = 1
| 502 |-------| +-----+-----+-----+-----+
+--------+ +-----------▲
| | 43 48 52 56
351 | 43 | +-----+-----+-----+-----+
|temp[2] |= *(temp + 2) | ? | ? | ? | ? | //for i = 2
| |-------| +-----+-----+-----+-----+
+--------+ +-----------▲
355 | |
| 9002 | 9002 9006 9010 9014
|temp[3] | +-----+-----+-----+-----+
| |= *(temp + 3) | ? | ? | ? | ? | //for i = 3
+--------+ | +-----+-----+-----+-----+
+-----------▲
Again ? means garbage values.
Additional points:
1) You are casting returned address by malloc but in C you should avoid it. Read Do I cast the result of malloc? just do as follows:
test = malloc(k* sizeof(int*));
for (i = 0; i < k; i++){
test[i] = malloc(k * sizeof(int));
}
2) If you are allocating memory dynamically, you need to free memory explicitly when your work done with that (after freeing dynamically allocated memory you can't access that memory). Steps to free memory for test will be as follows:
for (i = 0; i < k; i++){
free(test[i]);
}
free(test);
3) This is one way to allocate memory for 2D matrix as array of arrays if you wants to allocate completely continues memory for all arrays check this answer: Allocate memory 2d array in function C
4) If the description helps and you want to learn for 3D allocation Check this answer: Matrix of String or/ 3D char array
Remember that arrays decays to pointers, and can be used as pointers. And that pointers can be used as arrays. In fact, indexing an array can be seen as a form or pointer arithmetics. For example
int a[3] = { 1, 2, 3 }; /* Define and initialize an array */
printf("a[1] = %d\n", a[1]); /* Use array indexing */
printf("*(a + 1) = %d\n", *(a + 1)); /* Use pointer arithmetic */
Both outputs above will print the second (index 1) item in the array.
The same way is true about pointers, they can be used with pointer arithmetic, or used with array indexing.
From the above, you can think of a pointer-to-pointer-to.type as an array-of-arrays-of-type. But that's not the whole truth, as they are stored differently in memory. So you can not pass an array-of-arrays as argument to a function which expects a pointer-to-pointer. You can however, after you initialized it, use a pointer-to-pointer with array indexing like normal pointers.
malloc is used to dynamically allocate memory to the test variable think of the * as an array and ** as an array of arrays but rather than passing by value the pointers are used to reference the memory address of the variable. When malloc is called you are allocating memory to the test variable by getting the size of an integer and multiplying by the number of ints the user supplies, because this is not known before the user enters this.
Yes it is perfectly Ok. test is pointer to pointer and so test[i] which is equivalent to writing test + i will be a pointer. For better understanding please have a look on this c - FAQ.
Yes indeed, int** is a pointer to a pointer. We can also say it is an array of pointers.
test = (int **) malloc(k * sizeof(int*));
This will allocate an array of k pointers first. malloc dynamically allocates memory.
test[i] = (int*) malloc(k * sizeof(int));
This is not necessary as it is enough to
test[i] = (int*) malloc(sizeof(int*));
Here we allocate each of the array places to point to a valid memory. However for base types like int this kind of allocation makes no sense. It is usefull for larger types (structs).
Each pointer can be accessed like an array and vice versa for example following is equivalent.
int a;
test[i] = &a;
(test + i) = &a;
This could be array test in memory that is allocated beginning at offset 0x10000000:
+------------+------------+
| OFFSET | POINTER |
+------------+------------+
| 0x10000000 | 0x20000000 | test[0]
+------------+------------+
| 0x10000004 | 0x30000000 | test[1]
+------------+------------+
| ... | ...
Each element (in this example 0x2000000 and 0x30000000) are pointers to another allocated memory.
+------------+------------+
| OFFSET | VALUE |
+------------+------------+
| 0x20000000 | 0x00000001 | *(test[0]) = 1
+------------+------------+
| ...
+------------+------------+
| 0x30000000 | 0x00000002 | *(test[1]) = 2
+------------+------------+
| ...
Each of the values contains space for sizeof(int) only.
In this example, test[0][0] would be equivalent to *(test[0]), however test[0][1] would not be valid since it would access memory that was not allocted.
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.
int** is a pointer to a pointer of int. take a look at "right-left" rule