Sunday, 18 February 2018

c - Right syntax for allocation



If I take the 2 following snipped codes below (which are equivalent) :



double ***x;
x = malloc(N * sizeof(*x));
for (i = 0; i < size_y; i++) {
x[i] = malloc(N * sizeof(**x));



and



double ***x;
x = malloc(N * sizeof(double*));
for (i = 0; i < size_y; i++) {
x[i] = malloc(N * sizeof(double**));


Does the syntax for the first one above should be rather :




double ***x;
x = malloc(N * sizeof(*x));
for (i = 0; i < size_y; i++) {
x[i] = malloc(N * sizeof(*x));


I mean, for x, x[i] and x[i][j] malloc allocation, syntax will stay "sizeof(*x)", is this right ?



??




and does the second one should be :



double ***x;
x = malloc(N * sizeof(double**));
for (i = 0; i < size_y; i++) {
x[i] = malloc(N * sizeof(double*));


??




I saw this syntax from this link




It is safer becuse you don't have to mention the type name twice and
don't have to build the proper spelling for "dereferenced" version of
the type. For example, you don't have to "count the stars" in



int *****p = malloc(100 * sizeof *p);



Compare that to the type-based sizeof in




int *****p = malloc(100 * sizeof(int ****));



where you have too make sure you used the right number of * under
sizeof.




regards



UPDATE 1 :




I have got in one answer below the syntax as a pattern :



p = malloc(N * sizeof *p);


Does spaces (between N, sizeof and *p) and the abscence of parenthsesis for sizeof *p (instead of sizeof(*p)) have to be strictly applied for syntax of this allocation ?



In my code, I did :




 /* Arrays */
double** x;
double** x0;

/* Allocation of 2D arrays */
x = malloc(size_tot_y*sizeof(*x));
x0 = malloc(size_tot_y*sizeof(*x0));

for(i=0;i<=size_tot_y-1;i++)
{

x[i] = malloc(size_tot_x*sizeof(**x));
x0[i] = malloc(size_tot_x*sizeof(**x0));
}


As you can see, I used parenthesis for sizeof and didn't use spaces between size_tot_*, sizeof and *p.



Does my syntax change anything to respect the pattern mentioned above ?



It may be a silly question but I would like to get a confirmation.




Thanks


Answer



The pattern is:



p = malloc(N * sizeof *p);


Replace p with the same thing in both cases. For example:




x[i] = malloc(N * sizeof *x[i]);


Sometimes people abbreviate *x[i] to **x using the knowledge that **x means *x[0], and x[0] and x[i] have the same size because all elements of an array must have the same type and therefore the same size.



But if you are not confident about all this then you can stick to the basic pattern and use *x[i].


No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...