I have read this post.
From that, I read this:
From C99: 6.2.7.27
A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.39) Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements. (emphasis mine)
My interpretation of the parts important to me for the purpose of this question seem to say
if I have:
int *a, **b;
registration and alignment are guaranteed, and that all of these statements are true;
sizeof(a)==sizeof(*a)&&
sizeof(int *)==sizeof(b)&&
sizeof(*b)==sizeof(**b);// all essentially int pointers,
// and would be equal
but if I have:
int *a;
float*b;
registration and alignment are not guaranteed. i.e.:
sizeof(a)!=sizeof(b)&&
sizeof(float *)!=sizeof(int *)&&
sizeof(*b)!=sizeof(*a);//all pointers, but not of compatible types
//therefore not guaranteed to be equal.
The reason I ask is because of this discussion,
where I posted an answer showing a function that creates a 3D array:
int *** Create3D(int p, int c, int r)
{
int ***arr;
int x,y;
arr = calloc(p, sizeof(arr));
for(x = 0; x < p; x++)
{
arr[x] = calloc(c ,sizeof(arr));
for(y = 0; y < c; y++)
{
arr[x][y] = calloc(r, sizeof(int));
}
}
return arr;
}
Is the following statement safe in terms of using sizeof()?
arr = calloc(p, sizeof(arr));
Or, even though only int
types are used, should it be:
arr = calloc(p, sizeof(int **));
or:
arr = calloc(p, sizeof *arr);
The question:
Given arr
is declared as int ***
:
For allocating memory, as long as type stays int
is there any danger of using any of the variations of int pointer (int *, int **, arr, *arr, int ***
) as the argument to sizeof ?
Is one form preferred over the other? (please give reasons other than style)